360 Commits

Author SHA1 Message Date
04cb699081 该设备类型下已有设备,无法修改设备类型名称!!! 2026-02-04 17:28:08 +08:00
0f0dd4c6b1 hby100japp功能2 2026-02-04 15:49:53 +08:00
2db37a75d2 hby100japp功能 2026-02-04 15:27:43 +08:00
696bbb4aa4 hby100j功能语音管理 2026-02-03 16:29:46 +08:00
ee445dc0d2 获取音频时长2 2026-02-02 16:09:25 +08:00
897561ba89 获取音频时长 2026-02-02 16:08:43 +08:00
2e575f78b1 语音管理 2026-02-02 16:06:11 +08:00
6fd7f8ca94 配置文件修改 2026-01-30 16:54:25 +08:00
9936a5ad13 新增mac地址 2026-01-30 16:53:20 +08:00
c267fe0c14 配置文件 2026-01-30 16:50:01 +08:00
e80830e76c Merge remote-tracking branch 'origin/6170' into 6170 2026-01-30 16:08:07 +08:00
dyf
346792d5c1 Merge pull request 'feat(device): 新增阿里云语音通知功能并扩展设备查询接口' (#24) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #24
2026-01-30 16:06:57 +08:00
cb87871982 feat(device): 新增阿里云语音通知功能并扩展设备查询接口
- 集成阿里云语音服务,实现TTS语音拨号功能
- 添加异步报警拨号机制,支持SOS紧急呼叫
- 新增按设备名称查询设备的接口和SQL
- 扩展设备类型统计和批量查询功能
- 添加租户ID字段支持多租户设备管理
- 配置阿里云语音API依赖和客户端单例模式
2026-01-30 16:03:13 +08:00
437ab110b7 Merge remote-tracking branch 'origin/6170-protocol' into 6170
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/global/mqtt/config/MqttInboundConfiguration.java
#	fys-admin/src/main/java/com/fuyuanshen/global/mqtt/rule/bjq/BjqAlarmRule.java
2026-01-30 13:48:33 +08:00
dyf
b280038502 Merge pull request 'fix(controller): 修复新增设备日志注解配置' (#23) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #23
2026-01-28 16:33:25 +08:00
3e119b1dd8 feat(device): 添加设备图片字段映射
- 在设备服务实现中添加设备图片字段的赋值逻辑
- 将设备类型中的图片信息同步到设备对象中
2026-01-19 16:39:01 +08:00
cab0884d7f fix(controller): 修复新增设备日志注解配置
- 将 @Operation 注解替换为 @Log 注解以正确记录操作日志
- 保持新增设备功能的核心逻辑不变
- 确保日志标题正确显示为"新增设备"
2026-01-15 17:21:46 +08:00
88650c3d9f 代码优化 2026-01-14 18:36:23 +08:00
dyf
ca11ef0e35 Merge pull request 'feat(equipment): 添加设备图片上传功能' (#22) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #22
2026-01-12 11:15:56 +08:00
ef2dc6a6f6 feat(equipment): 添加设备图片上传功能
- 在DeviceType实体类中新增devicePic字段用于存储设备图片
- 修改控制器方法参数从RequestBody改为ModelAttribute以支持文件上传
- 更新DeviceTypeForm表单类添加MultipartFile类型的file字段
- 实现图片上传服务集成OSS存储和文件哈希处理
- 添加HTTP到HTTPS的URL强制转换机制
- 更新数据库操作逻辑以支持图片路径存储
- 在设备创建流程中集成设备类型图片信息传递
2026-01-12 11:06:44 +08:00
dff37b245a Merge branch 'dyf-device' into 6170 2025-12-26 16:22:00 +08:00
d7c4d22de3 该设备类型下已有设备,无法修改设备类型名称!!! 2025-12-26 16:21:33 +08:00
6a058318f2 设备记录列表显示问题修改 2025-12-26 15:54:14 +08:00
f2d74b8f17 Merge branch 'dyf-device' into 6170 2025-12-22 15:09:39 +08:00
af42a2199c 根据用户ID查询菜单 2025-12-22 15:09:07 +08:00
aaf142ca67 提交 2025-12-19 17:55:48 +08:00
c0dfe36b59 cn.idev.excel 2025-12-19 16:21:56 +08:00
c480bda112 围栏进出记录 2025-12-19 14:06:01 +08:00
8c636d0484 设备维修记录 2025-12-12 14:55:03 +08:00
0c474ae1f3 维修时间 2025-12-11 15:24:46 +08:00
b85664900e 分页查询围栏进出记录列表 2025-12-10 09:39:00 +08:00
dyf
035b24fedd Merge pull request 'feat(equipment): 新增高德轨迹服务相关功能与设备终端管理' (#21) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #21
2025-12-03 16:52:09 +08:00
e920cfb860 feat(equipment): 新增高德轨迹服务相关功能与设备终端管理
- 新增 AmapTrackUtil 工具类,封装高德猎鹰轨迹服务 API 调用
- 在 Device 实体中增加高德服务、终端、轨迹 ID 字段(sid, tid, trid)
- 新增设备终端分页查询接口 /pageTerminal 及对应实现
- 新增围栏与设备关联实体 DeviceFenceTerminal 及 Mapper
- 扩展 DeviceGeoFence 相关注入高德服务及围栏 ID 字段
- 新增添加/删除围栏终端绑定接口及业务逻辑
- 新增轨迹服务模块(TrackService)包括 Controller、Service、BO、DTO 等完整结构
- 在 DeviceMapper.xml 中补充终端相关字段查询及筛选条件
- 新增 TerminalDeviceBo、TerminalDelBo、TerminalQueryBo 等数据传输对象
- 补充设备查询条件支持高德终端状态及服务 ID 过滤
- 新增围栏终端关联表 device_fence_terminal 并注册至菜单配置
- 完善设备分配逻辑以兼容角色权限判断及终端信息展示
2025-12-03 11:39:18 +08:00
b33ee00dbd APP文件上传 2025-12-01 10:34:41 +08:00
c8f9cc4f31 Merge branch 'dyf-device' into 6170 2025-11-28 10:17:42 +08:00
26d2f05c4e 绑定状态 2025-11-28 10:13:26 +08:00
d57d17dc50 登录提示去掉 2025-11-28 09:15:35 +08:00
20ddbf6e05 app注销删除相关联数据2 2025-11-27 11:16:07 +08:00
63a9d2f8f9 导出图片压缩 2025-11-27 11:00:34 +08:00
7753444f25 Merge branch 'dyf-device' into jingquan
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/controller/AppVideoController.java
2025-11-25 14:52:10 +08:00
bf182ebc89 强制将HTTP替换为HTTPS 2025-11-25 14:51:10 +08:00
dyf
d5a29feca3 Merge pull request 'jingquan' (#20) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #20
2025-11-25 14:47:00 +08:00
0457877c09 merge upstream 2025-11-24 08:30:34 +08:00
1e9e815314 uploadVideo 2025-11-21 16:24:07 +08:00
b18ab98feb 导出设备数据 2025-11-21 13:36:13 +08:00
7c6f3be844 merge upstream 2025-11-20 16:25:33 +08:00
aa69b552aa Merge remote-tracking branch 'liwenlong-fys/jingquan' into jingquan 2025-11-20 16:25:04 +08:00
3dd0d4cc90 feat(video): 支持BGR565格式视频处理及MQTT设备确认消息更新
- 新增BGR565格式转换逻辑,支持RGB565与BGR565两种颜色格式- 视频上传接口增加code参数,默认值为1(RGB565)
- 在VideoProcessUtil中实现convertFramesToBGR565方法
- 添加bgr565ToMp4工具方法用于将BGR565数据编码为MP4文件
- MQTT规则新增对“设备已收到通知”的处理逻辑
- 设备确认消息后更新数据库日志状态并推送SSE消息
- 引入ScheduledExecutorService延时推送SSE消息- 增加设备日志和设备Mapper依赖以支持数据操作
2025-11-20 16:24:45 +08:00
00a4394b43 新增设备 2025-11-20 16:15:15 +08:00
2376a3b42a 修改设备类型 2025-11-20 10:11:14 +08:00
359cabbd2c feat(video): 支持BGR565格式视频处理- 新增code参数用于指定视频转码格式
- 实现BGR565格式的帧数据转换逻辑
- 添加convertFramesToBGR565和convertToBGR565方法
- 支持将BGR565数据通过FFmpeg生成MP4文件- 更新VideoProcessUtil工具类以支持两种颜色格式
- 在视频处理服务中记录处理日志及hex列表信息
2025-11-20 09:06:05 +08:00
76c11fff15 Merge remote-tracking branch 'upstream/6170' into 6170 2025-11-19 17:17:40 +08:00
a0ab5e9fe0 app注销删除相关联数据 2025-11-19 17:17:34 +08:00
891ee7c1c9 Merge branch 'dyf-device' into 6170 2025-11-19 10:56:12 +08:00
a145c372b8 优化设备导出 2025-11-19 10:55:44 +08:00
3798e52ee0 导入设备数据 2025-11-18 15:34:46 +08:00
6488b8a724 Merge branch 'dyf-device' into 6170 2025-11-12 11:25:55 +08:00
6d58268874 根据新增业务对象插入设备语音 2025-11-11 15:10:15 +08:00
88b54a49f4 Merge branch 'dyf-device' into 6170
# Conflicts:
#	fys-admin/src/main/resources/application-prod.yml
2025-11-11 14:34:19 +08:00
56dbfbde71 prod 2025-11-11 14:33:10 +08:00
dce043f63d Merge branch 'dyf-device' into 6170 2025-11-11 10:51:57 +08:00
77626673e9 设备语音 2025-11-11 10:51:28 +08:00
759c72fc65 Merge branch 'dyf-device' into 6170 2025-11-10 10:37:43 +08:00
1be80be309 灯光模式 5 2025-11-10 10:37:03 +08:00
ec28ab1092 设备协议 2025-11-10 08:37:42 +08:00
92df1c8668 Merge branch 'dyf-device' of http://47.107.152.87:3000/dyf/fys-Multi-tenant into dyf-device 2025-11-08 09:48:18 +08:00
cc2b7664a8 处理MQTT消息 2025-11-08 09:48:12 +08:00
33d6108172 处理MQTT消息 2025-11-08 09:38:19 +08:00
70c416779f Merge branch 'dyf-device' into 6170 2025-11-07 17:11:45 +08:00
ee85961eeb Merge branch 'main' into dyf-device 2025-11-07 17:11:21 +08:00
004079f7f4 Merge branch 'jingquan'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/service/AudioProcessService.java
2025-11-07 17:10:54 +08:00
264d0135d9 获取设备分享详细信息 2025-11-07 17:07:33 +08:00
dyf
4961ec47f8 Merge pull request 'feat(file): 新增文件哈希去重与文本提取功能- 在多个模块中引入 FileHashUtil 并用于文件上传前的哈希计算' (#19) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #19
2025-11-07 17:06:27 +08:00
f25afe0e9d feat(file): 新增文件哈希去重与文本提取功能- 在多个模块中引入 FileHashUtil 并用于文件上传前的哈希计算
- 优化文件上传逻辑,实现基于哈希的秒传机制
- 新增音频服务中的文本提取方法,支持 txt 和 docx 格式
- 使用流式解析技术处理大文件内容,避免内存溢出
-为 AppVideoController 添加 /extract 接口用于文本内容提取
- 完善文件哈希工具类,增强线程安全性与异常处理
- 调整 SysOssService 的 updateHash 方法以支持复用逻辑- 统一构建 SysOssVo 实体时的哈希字段设置逻辑
2025-11-07 16:59:07 +08:00
e265dea0ec BJQ6075 设备控制类 2025-11-07 15:53:13 +08:00
c7ff118bfe BJQ6075 设备控制类 2025-11-06 10:39:12 +08:00
1dc3386284 6075 mqtt 2025-11-05 17:55:59 +08:00
c4957aa3aa 音频处理服务 2025-10-31 08:50:08 +08:00
f4369f7581 分享设备bug修改 2025-10-30 14:27:01 +08:00
df28eed305 prod配置文件 2025-10-28 10:51:05 +08:00
07e60cf7f0 Merge branch 'dyf-device' into 6170 2025-10-28 10:33:15 +08:00
5d42f8a1e1 Merge branch 'jingquan' into dyf-device 2025-10-28 10:32:31 +08:00
dyf
f2a5e63a41 Merge pull request 'feat(equipment): 添加阿里巴巴TTS语音合成工具类' (#18) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #18
2025-10-28 10:31:37 +08:00
467a7befb1 提交2 2025-10-28 10:29:12 +08:00
107ddf8851 feat(app): 添加防重复提交注解
- 在视频上传接口添加 @RepeatSubmit 注解
- 在音频上传接口添加 @RepeatSubmit 注解
- 在文字转音频接口添加 @RepeatSubmit 注解
- 设置重复提交间隔为2 秒- 添加重复提交提示信息"请勿重复提交!"
2025-10-27 09:00:36 +08:00
a85e74c5e6 在线状态任务3 2025-10-25 08:35:25 +08:00
9bbddee1d5 feat(equipment): 添加阿里巴巴TTS语音合成工具类
- 实现文本转语音功能,支持多种声音、语速、音量等参数调节
- 集成阿里云TTS服务,支持访问令牌自动刷新与缓存
- 提供HTTP客户端配置与请求处理逻辑
- 支持生成标准PCM数据及WAV格式音频文件
- 实现音频文件保存与错误处理机制
- 添加参数校验与日志记录功能
- 集成Redis缓存管理访问令牌- 支持URL编码与请求构建逻辑
- 实现响应处理与音频数据写入文件功能
- 添加静默删除临时文件与错误响应处理机制
2025-10-24 11:22:35 +08:00
da0833a400 Merge remote-tracking branch 'origin/6170' into 6170 2025-10-13 16:15:26 +08:00
418fb55bf0 导出电子围栏列表 2025-10-13 14:25:07 +08:00
1d50981a84 在线状态任务2 2025-10-13 14:14:51 +08:00
2f80c450c5 最多同时加载5张图片 2025-10-13 10:48:53 +08:00
09cbdf267b 设备绑定提示 2025-10-12 13:37:18 +08:00
156fdbb53b 历史轨迹mac地址支持模糊查询 2025-10-11 16:33:57 +08:00
3246127893 设备解绑 2025-10-11 16:16:06 +08:00
dab0440128 绑定bug修复 2025-10-11 16:07:14 +08:00
dyf
740a638444 Merge pull request 'fix(device):修复SOS报警类型判断逻辑' (#17) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #17
2025-10-11 13:35:08 +08:00
a3d44a157a fix(device):修复SOS报警类型判断逻辑
- 简化报警类型判断,固定为SOS类型
- 移除不必要的shake类型判断逻辑
2025-10-11 13:23:51 +08:00
cc23f082a6 Merge remote-tracking branch 'upstream/6170' into 6170 2025-10-11 11:06:15 +08:00
1bc7dc676e 控制中心查询 2025-10-11 11:06:07 +08:00
5cdacad468 获取设备使用频次统计 2025-10-11 10:32:16 +08:00
62af38cbf0 Merge branch 'dyf-device' into 6170 2025-10-11 09:05:38 +08:00
04a21567aa 设备所属分组 2025-10-11 09:04:48 +08:00
5b4fa38dbd 设备告警 2025-10-10 15:46:25 +08:00
2c3effa683 历史轨迹1 2025-10-10 09:26:52 +08:00
7b8c626cb6 Merge branch 'jingquan' into dyf-device 2025-10-09 14:45:15 +08:00
dyf
9642908035 Merge pull request 'feat(app): 实现系统版本管理功能-Dto 新增 SystemVersion 数据传输对象- 修改 AppAuthController 的 getAppVersion 接口,从 Redis 获取版本信息' (#16) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #16
2025-10-09 14:44:18 +08:00
85b2e2b976 设备告警1 2025-10-09 13:31:37 +08:00
88ac0236bd feat(app): 实现系统版本管理功能-Dto 新增 SystemVersion 数据传输对象- 修改 AppAuthController 的 getAppVersion 接口,从 Redis 获取版本信息
- 新增 DeviceXinghanController 的 VersionSettings 接口,用于更新版本信息到 Redis- 引入 FastJSON 和 Redis 工具类支持版本信息的序列化与缓存
- 添加权限注解控制版本更新接口访问
- 定义全局 Redis 键常量用于版本信息存储
2025-10-09 11:09:07 +08:00
609a3e4058 设备在线状态2 2025-10-09 09:44:48 +08:00
68cf78f3f2 设备在线状态5 2025-10-08 17:27:43 +08:00
c9857a679c 设备在线状态4 2025-10-08 15:08:31 +08:00
6439a96e3d 设备在线状态3 2025-10-08 15:07:54 +08:00
9f0155a6e3 Merge branch 'dyf-device' into 6170 2025-10-08 14:12:09 +08:00
6c99cef65d 解除告警 2025-10-08 14:11:11 +08:00
840c4fd68f 设备在线状态2 2025-10-08 13:53:03 +08:00
dc0fe96652 设备在线状态 2025-10-08 13:38:07 +08:00
cf883bfa00 Merge remote-tracking branch 'upstream/6170' into 6170 2025-10-08 11:48:16 +08:00
6a6397da23 控制查询条件加模糊查询 2025-10-08 11:48:05 +08:00
d701a834b3 设备IMEI 模糊查询 2025-10-08 09:37:18 +08:00
e1ac87e5f2 在线状态 2025-10-07 16:11:06 +08:00
5c3a35c83e 在线状态 2025-10-07 16:09:59 +08:00
2c0eff2b2c Merge remote-tracking branch 'origin/6170' into 6170 2025-10-07 15:50:26 +08:00
37e07d2706 控制中心优化2 2025-10-07 15:50:16 +08:00
dyf
5c0c4e40e4 Merge pull request 'fix(device):优化Redis缓存更新逻辑' (#15) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #15
2025-10-07 15:46:56 +08:00
eceedae676 fix(device):优化Redis缓存更新逻辑
- 删除原有的直接设置缓存列表逻辑
- 新增先删除后写入的缓存更新策略- 统一使用变量存储Redis键值避免重复拼接- 保持原有缓存过期时间设置为5分钟
2025-10-07 15:29:19 +08:00
dfa5b446f9 控制中心优化 2025-10-07 09:50:49 +08:00
9afc0222d5 app批量上传logo 2025-09-30 17:53:28 +08:00
2cfcea65f1 Merge branch '6170' into dyf-device 2025-09-30 16:10:13 +08:00
dyf
9b72a6ebd2 Merge pull request 'feat(device): 新增设备类型查询与设备添加功能' (#14) from liwenlong/fys-Multi-tenant:jingquan into jingquan
Reviewed-on: #14
2025-09-30 16:06:10 +08:00
13db094336 feat(device): 新增设备类型查询与设备添加功能
- 在AppDeviceXinghanController中新增查询所有设备类型接口
- 实现新增设备功能,包含设备MAC和IMEI唯一性校验- 添加设备类型权限验证逻辑
- 完善设备绑定状态和主题设置
- 在DeviceXinghanBizService中实现设备分配记录保存
- 优化文件批量插入逻辑,支持是否批量删除历史数据- 增加文件删除功能,支持根据ID列表删除业务文件
- 缩短MQTT消息去重时间窗口至3秒
- 在设备维修记录查询条件中增加维修人员模糊查询- 调整设备消息发送数据顺序,单位名称移至首位
2025-09-30 15:59:24 +08:00
a1d6604520 app产品参数修改 2025-09-30 15:42:59 +08:00
b0e51e73c7 岗位信息1 2025-09-30 13:21:43 +08:00
dba537b83f 发送信息和告警故障5 2025-09-30 09:57:45 +08:00
d9b69ddc4e 不同的一级目录下的分组应当可以重名 2025-09-29 17:53:26 +08:00
6cec86bafe Merge remote-tracking branch 'upstream/6170' into jingquan 2025-09-29 13:57:29 +08:00
608aa8449a Merge branch 'main' into dyf-device 2025-09-29 09:26:49 +08:00
dyf
6084f11e62 Merge pull request 'jingquan' (#13) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: #13
2025-09-29 09:26:04 +08:00
994e63bcde Merge branch '6170' of http://47.107.152.87:3000/dyf/fys-Multi-tenant into 6170 2025-09-29 09:24:52 +08:00
d6520d777a 发送信息和告警故障4 2025-09-29 09:17:20 +08:00
1898fe5db9 Merge branch '6170' into dyf-device 2025-09-28 18:19:21 +08:00
7d56e2e80e 发送信息和告警故障3 2025-09-28 17:18:47 +08:00
233e0e32b0 发送信息和告警故障2 2025-09-28 16:19:28 +08:00
cb2acdb3f4 Merge remote-tracking branch 'liwenlong-fys/jingquan' into jingquan 2025-09-28 16:11:52 +08:00
a4596b9c90 feat(device): 实现设备批量控制指令发送功能- 新增批量发送设备控制指令方法 sendCommandBatch- 支持设备离线状态检查和异常处理
- 添加设备操作日志记录和报警创建- 实现设备SOS档位批量设置接口
- 在设备指令处理中增加消息去重机制
- 优化设备报警处理的分布式锁逻辑
- 完善设备数据规则中的并发控制
2025-09-28 16:11:34 +08:00
5230a95865 自动报警 2025-09-28 15:28:19 +08:00
4d2b7c6adf 设备是否正在告警 2025-09-28 11:53:24 +08:00
461fd9364c Merge remote-tracking branch 'upstream/6170' into 6170 2025-09-27 15:40:39 +08:00
ad81647939 发送信息和告警故障 2025-09-27 15:40:31 +08:00
2d59397de5 大屏数据 2025-09-27 15:30:12 +08:00
b7c81419a4 围栏进出记录-导出-报错 2025-09-26 11:48:20 +08:00
3859c20081 Merge branch 'dyf-device' into 6170 2025-09-26 09:33:07 +08:00
3bdabb04e2 设备列表-导出excel 缺少绑定状态,excel表头顺序按列表展示 2025-09-26 09:32:42 +08:00
e124694e67 Merge branch 'main' into dyf-device 2025-09-26 08:36:00 +08:00
dyf
e528cd04e9 Merge pull request 'jingquan' (#12) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: #12
2025-09-26 08:34:05 +08:00
735199b9e0 控制中心查询3 2025-09-25 10:58:57 +08:00
a69c665d8b 控制中心查询2 2025-09-25 10:58:25 +08:00
5a52129fd0 控制中心查询 2025-09-25 09:21:11 +08:00
7eb5e6095a feat(device): 新增报警类型枚举并优化设备指令处理逻辑
- 新增 AlarmTypeEnum 枚举类,定义 SOS 和静止报警类型
-优化 AppAuthController 中版本信息解析逻辑,增强空值处理
- 统一设备指令接口参数类型为 DeviceXinghanInstructDto
- 在 DeviceXinghanBizService 中实现 SOS 报警创建逻辑
-重构 XinghanDeviceDataRule 报警处理流程,使用统一枚举类型- 添加蓝牙模式下 SOS 指令的特殊处理逻辑- 完善报警 Redis 缓存键构建和续期机制
2025-09-25 08:31:32 +08:00
91f0241181 feat(mqtt): 添加电池电量百分比字段并适配控制列表显示
- 在 MqttXinghanJson 中新增 batteryPercentage 字段- 在 XinghanDeviceDataRule 中设置 batteryPercentage 值
- 适配控制百分比列表显示电池电量信息
2025-09-23 15:55:01 +08:00
baa341c2bf feat(equipment): 实现设备维修记录图片管理和报警处理功能
-重构文件哈希工具类路径并优化上传逻辑,支持秒传
- 新增维修记录图片ID列表字段及删除旧图片逻辑- 设备维修记录查询增加设备名称模糊搜索条件
-日期查询条件添加格式化注解支持 yyyy-MM-dd- MQTT规则中新增SOS与静止报警处理机制
- 实现报警生命周期管理(开始/结束)及Redis缓存控制
- 添加报警信息入库和位置解析功能
- 优化设备状态数据解析与经纬度异步存储逻辑
2025-09-23 14:21:05 +08:00
9c98fa9077 Merge branch 'dyf-device' into 6170 2025-09-23 13:58:09 +08:00
89f08c2d91 导入导出设备数据 2025-09-23 13:56:34 +08:00
135e6d6899 设备分享 2025-09-23 11:42:44 +08:00
49e9066033 feat(equipment): 实现设备维修记录图片管理和报警处理功能
-重构文件哈希工具类路径并优化上传逻辑,支持秒传
- 新增维修记录图片ID列表字段及删除旧图片逻辑- 设备维修记录查询增加设备名称模糊搜索条件
-日期查询条件添加格式化注解支持 yyyy-MM-dd- MQTT规则中新增SOS与静止报警处理机制
- 实现报警生命周期管理(开始/结束)及Redis缓存控制
- 添加报警信息入库和位置解析功能
- 优化设备状态数据解析与经纬度异步存储逻辑
2025-09-23 11:31:11 +08:00
e2821566c8 事件地址 2025-09-22 18:18:05 +08:00
5b3a92c80d 查询所有设备类型 2025-09-22 16:34:32 +08:00
9d642f4913 分页查询围栏进出记录列表 2025-09-22 15:58:00 +08:00
f07ec53645 控制中心设备绑定修改3 2025-09-22 14:05:39 +08:00
74b0059aca 控制中心设备绑定修改2 2025-09-22 14:03:44 +08:00
8e66f1ca28 控制中心设备绑定修改 2025-09-22 12:41:54 +08:00
1b33356a2a 在线状态修改 2025-09-22 11:02:26 +08:00
5f36c25550 内容(报警信息) 2025-09-20 14:35:23 +08:00
9058dcfcb1 设备告警 2025-09-20 11:45:11 +08:00
3e19cd9db2 设置图片路径 2025-09-19 09:43:52 +08:00
397f227bfb Merge branch 'dyf-device' into 6170 2025-09-18 15:26:04 +08:00
1b2bf542fa 个人中心修改密码2 2025-09-18 15:25:32 +08:00
7d4bc1f8ad Merge branch 'liwenlong-jingquan'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/controller/AppAuthController.java
#	fys-admin/src/main/java/com/fuyuanshen/web/service/device/DeviceBizService.java
#	fys-modules/fys-equipment/src/main/resources/mapper/equipment/DeviceAlarmMapper.xml
#	fys-modules/fys-equipment/src/main/resources/mapper/equipment/DeviceMapper.xml
2025-09-18 12:03:43 +08:00
4d9038567f 根据提供的代码差异信息,以下是符合Angular commit规范的commit message:
```
feat(app): 添加获取app版本接口及视频处理控制器

新增功能:
- 在AppAuthController中添加了获取app版本信息的接口`/version`。- 新增AppVideoController用于处理视频上传和帧提取。

修改内容:
- 在AppAuthController中引入了ISysDictTypeService服务。
- 在DeviceBizService中更新了设备通信模式的判断逻辑。
- 修改了DeviceAlarmMapper.xml和DeviceMapper.xml中的SQL查询语句以支持更多通信模式。
- 更新了DeviceXinghanBizService中的人员信息登记逻辑,并添加了获取设备详细信息的方法。
- 在DeviceXinghanController中添加了获取设备详细信息的接口`/info/{id}`。
- 更新了MqttXinghanJson类中的字段命名。
- 在pom.xml中添加了javacv相关的依赖。

修复问题:
- 注释掉了AppSmsAuthStrategy中的登录检查逻辑。
```

这个commit message包含了类型(feat)、作用范围(app)以及简短的描述。同时在body部分详细说明了新增的功能、修改的内容以及修复的问题。
2025-09-18 11:40:12 +08:00
630c6a8a35 角色管理员 2025-09-18 11:25:40 +08:00
11e48acc81 个人中心修改密码 2025-09-18 08:54:29 +08:00
540a6fc1da 密码长度验证 2025-09-17 17:43:17 +08:00
aeea8f9072 登录优化 2025-09-17 10:56:25 +08:00
b463e97d28 配置文件mqtt端口修改 2025-09-16 17:35:29 +08:00
e1b147b6be Merge branch 'dyf-device' into 6170 2025-09-16 17:05:19 +08:00
23b48cfb06 设备告警 2025-09-16 17:04:45 +08:00
4106260e5f 在线状态修改优化4 2025-09-15 17:49:28 +08:00
07449e4a1e 查询围栏进出记录列表 2025-09-15 16:49:38 +08:00
b278a3087e 报警事项 2025-09-15 14:59:08 +08:00
dca5a6c48d 在线状态修改优化3 2025-09-15 09:43:15 +08:00
15b3348989 Merge branch 'dyf-device' into 6170 2025-09-15 09:41:56 +08:00
9fbb0aefcf 检查设备位置与围栏的关系 2025-09-15 09:41:10 +08:00
4004aa1090 在线状态修改优化2 2025-09-13 16:51:56 +08:00
39c8375f08 在线状态修改优化 2025-09-13 16:46:05 +08:00
64c81ac44e 在线状态修改2 2025-09-13 15:51:34 +08:00
41eb3d9a33 在线状态修改 2025-09-13 15:37:48 +08:00
8597dc5a9f 导出围栏进出记录列表 2025-09-12 14:50:42 +08:00
01a1a6e25b 查询围栏进出记录 2025-09-12 11:48:39 +08:00
1722f92328 电子围栏-位置检查 2025-09-12 09:04:47 +08:00
ee8840d657 Merge remote-tracking branch 'origin/6170' into 6170 2025-09-11 14:43:02 +08:00
9b84296419 Merge branch 'main' into dyf-device 2025-09-11 14:41:41 +08:00
dyf
d48c7b389e Merge pull request 'jingquan' (#10) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: #10
2025-09-11 14:40:23 +08:00
ccdc25595d Merge remote-tracking branch 'origin/6170' into 6170 2025-09-11 14:38:06 +08:00
f1aad91421 修改绑定1 2025-09-11 14:37:40 +08:00
e2274bdf09 feat(web): 新增设备联调中心功能
- 新增设备联调中心相关控制器、服务、DTO和VO
- 实现设备列表查询、文件上传、操作视频添加、设备详情等功能
- 优化设备 logo 上传逻辑,支持批量上传
- 重构部分代码结构,提高可维护性
2025-09-11 11:07:58 +08:00
8a127b9d2d Merge branch 'dyf-device' into 6170 2025-09-11 10:56:29 +08:00
b8af6b511c 电子围栏 2025-09-11 10:54:56 +08:00
6bc1d5b20b 绑定设备 2025-09-10 09:56:39 +08:00
228e26df7f merge upstream 2025-09-09 17:23:23 +08:00
801b0267e6 设备分享3 2025-09-09 17:01:51 +08:00
fcbde4322d 今日报警总数 2025-09-09 16:39:43 +08:00
832234269d 获取设备使用数据 2025-09-09 16:06:34 +08:00
7e87971c0b 新增绑定设备 2025-09-09 15:02:46 +08:00
ebd8668178 在线设备 2025-09-09 11:03:38 +08:00
5e3307d2b0 设备分享2 2025-09-09 10:29:51 +08:00
040e44984e Merge branch 'dyf-device' into 6170
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/web/controller/device/DeviceShareController.java
2025-09-09 10:01:26 +08:00
f7a82ef138 设备操作记录 分页 2025-09-09 09:55:58 +08:00
91f787eec7 pageQuery 2025-09-08 17:37:01 +08:00
870f94b2d4 开始时间 2025-09-08 16:12:02 +08:00
395b2957c1 Merge remote-tracking branch 'origin/6170' into 6170 2025-09-06 16:19:35 +08:00
64a4485ced 设备分享 2025-09-06 16:19:12 +08:00
1e4ee840a3 Merge branch 'dyf-device' into 6170 2025-09-06 11:48:00 +08:00
374a03b83d 管理员 2025-09-06 11:46:13 +08:00
b945420446 离线状态变更3 2025-09-05 13:32:32 +08:00
c057af7cd0 离线状态变更2 2025-09-05 11:46:29 +08:00
452c37c4ca 离线状态变更 2025-09-04 18:40:08 +08:00
d5a9a92f9f feat(device): 新增设备控制相关接口
- 人员信息登记- 发送紧急通知
-上传设备 logo 图片
-静电预警档位设置- 照明档位设置- SOS 档位设置- 静止报警状态设置
2025-09-04 11:50:18 +08:00
429c0f1307 Merge branch 'dyf-device' into 6170 2025-09-04 11:29:55 +08:00
ff4db34e2a 型号字典用于APP页面跳转 2025-09-04 11:29:07 +08:00
377579dd14 Merge branch 'dyf-device' into 6170 2025-09-03 15:57:21 +08:00
00e345d5e5 Merge branch 'main' into dyf-device 2025-09-03 15:56:30 +08:00
dyf
1a2f35a092 Merge pull request 'jingquan' (#9) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: #9
2025-09-03 15:55:27 +08:00
bdbbd5a12f feat(equipment): 添加设备维修图片功能并优化维修记录相关接口- 新增 DeviceRepairImages 相关实体、Mapper 和 XML 文件- 重构 DeviceRepairRecords 相关接口和实现类,支持图片上传
- 新增 RepairImageType 枚举类
- 优化 DeviceRepairRecordsVo,增加图片列表和设备名称字段
2025-09-03 15:17:39 +08:00
98cb67b136 修改获取经纬度 2025-09-03 15:11:24 +08:00
d97928b38a 分配客户 接口注释 2025-09-03 09:45:17 +08:00
1d37bfb719 首页数据 2025-09-02 15:08:53 +08:00
98ef841f18 通讯方式 2025-09-02 10:32:17 +08:00
8462fed747 merge upstream 2025-09-02 09:06:54 +08:00
0787e4b205 Merge remote-tracking branch 'origin/dyf-device' into 6170
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/web/service/device/DeviceBizService.java
#	fys-modules/fys-equipment/src/main/java/com/fuyuanshen/equipment/domain/vo/LocationHistoryDetailVo.java
2025-09-02 08:51:41 +08:00
eca113d388 首页数据 2025-09-02 08:49:42 +08:00
127e26e0d4 首页数据 2025-09-01 16:03:46 +08:00
dfb5d8ac65 修改获取实时状态类型 2025-08-30 13:53:41 +08:00
896c501cd6 报警持续时间 2025-08-30 11:07:04 +08:00
d8686e3cbd Merge branch 'dyf-device' into 6170 2025-08-30 09:40:51 +08:00
c2ce9679c4 设备充放电记录 2025-08-30 09:39:41 +08:00
d66fb7d2c2 设备告警 2025-08-29 18:58:16 +08:00
400c53030a Merge remote-tracking branch 'origin/6170' into 6170 2025-08-29 16:49:44 +08:00
b5565da752 web端控制中心4 2025-08-29 16:49:16 +08:00
e17a64ad57 查询设备告警列表 2025-08-29 13:59:23 +08:00
3969e50566 查询设备分享列表(web) 2025-08-29 10:29:53 +08:00
760738bcdd 设备告警记录 2025-08-28 13:30:50 +08:00
765e0f8509 设备告警 2025-08-28 11:26:00 +08:00
2c565f5c2d 设备告警 2025-08-28 11:22:04 +08:00
7aa02635f2 feat(device): 优化设备人员信息发送逻辑
- 调整人员信息的顺序,符合兴汉设备接收数据的要求
- 添加设备上报人员登记信息的日志,方便问题追踪
2025-08-27 17:30:00 +08:00
626296adbc merge upstream 2025-08-27 15:28:40 +08:00
9bbed77170 refactor(fys-demo): 优化视频上传接口并修复 MQTT 报警信息发送逻辑
- 移除了 VideoUploadController 中的 @SaIgnore 注解,恢复权限控制- 优化了 XinghanSendAlarmMessageRule 中的 Redis 数据检查逻辑
2025-08-27 15:27:19 +08:00
837953bf3d 设备类型ID 2025-08-27 10:20:37 +08:00
8b25fd9ba4 设备操作记录 2025-08-27 09:25:08 +08:00
8a7565459b Merge branch '6170' of http://47.107.152.87:3000/dyf/fys-Multi-tenant into 6170 2025-08-27 09:09:20 +08:00
0bbac2b497 设备用户详情 2025-08-27 09:08:27 +08:00
364574eeae web端控制中心3 2025-08-27 08:59:29 +08:00
a5b8cdffec refactor(device): 优化设备发送告警信息功能
- 批量查询设备,减少数据库交互次数
- 优化设备状态检查逻辑,提高效率
- 封装单个设备发送告警信息的逻辑,提高代码可读性- 使用 Redis 和 MQTT 时增加异常处理,提高系统稳定性
- 优化日志记录和异常提示,便于问题排查
2025-08-26 17:12:36 +08:00
f9d9dadf08 绑定设备分组 2025-08-26 10:00:35 +08:00
e4df695f5e 绑定设备分组 2025-08-26 09:26:33 +08:00
f839883f82 feat(device): 新增发送紧急通知功能
- 在 AppDeviceXinghanController 中添加 sendAlarmMessage接口
- 在 DeviceXinghanBizService 中实现 sendAlarmMessage 方法
- 新增 XinghanSendAlarmMessageRule 类用于处理紧急通知发送逻辑
- 在 DeviceRedisKeyConstants 中添加 DEVICE_ALARM_MESSAGE_KEY_PREFIX 常量
- 修改 XinghanDeviceDataRule 和 XinghanSendMsgRule 中的相关逻辑
2025-08-25 14:18:54 +08:00
74cefe9cc3 设备详情 2025-08-25 13:42:24 +08:00
9b476e98ba 型号字典用于PC页面跳转 2025-08-25 11:40:59 +08:00
d962c6ead5 查询分享用户数 2025-08-25 10:19:57 +08:00
1246ac5cf7 @Schema(title = "ID", hidden = true) 2025-08-23 17:33:35 +08:00
7607a0c9c0 Merge remote-tracking branch 'origin/6170' into 6170
# Conflicts:
#	fys-modules/fys-equipment/src/main/java/com/fuyuanshen/equipment/domain/query/DeviceQueryCriteria.java
2025-08-23 16:40:42 +08:00
8811c30a97 web端控制中心2 2025-08-23 16:39:30 +08:00
d05e046112 Merge branch 'main' into dyf-device 2025-08-22 18:28:40 +08:00
dyf
e86eff48ee Merge pull request 'jingquan' (#8) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: #8
2025-08-22 18:26:44 +08:00
aef16cf6b4 Merge remote-tracking branch 'liwenlong-fys/jingquan' into jingquan 2025-08-22 18:10:10 +08:00
95aa01e1c2 feat(device): 新增星汉设备控制功能
- 添加星汉设备控制器 AppDeviceXinghanController- 实现星汉设备业务逻辑 DeviceXinghanBizService
- 增加开机 LOGO 下发规则 XinghanBootLogoRule
- 添加设备发送消息规则 XinghanSendMsgRule
- 更新 MQTT 命令类型常量 XingHanCommandTypeConstants
- 修改设备状态 JSON 结构 MqttXinghanJson
2025-08-22 18:09:08 +08:00
2965b454cf web:设备分组 接口文档 2025-08-22 16:37:58 +08:00
b83be496b6 出厂日期 2025-08-22 09:58:27 +08:00
4965d78c51 设备所属分组 2025-08-22 09:40:52 +08:00
9dee7ad102 管理员 2025-08-21 17:55:59 +08:00
dyf
e9542c70e9 Merge pull request 'jingquan' (#7) from liwenlong/fys-Multi-tenant:jingquan into dyf-device
Reviewed-on: #7
2025-08-21 17:54:48 +08:00
dyf
51297f269d Merge branch 'dyf-device' into jingquan 2025-08-21 17:54:39 +08:00
4077fd303f merge upstream 2025-08-21 17:44:57 +08:00
f1a19f95f5 feat(mqtt): 新增星汉设备数据处理规则和解析逻辑- 添加 MqttXinghanCommandType 枚举类,用于识别和处理星汉设备的命令类型
- 新增 MqttXinghanJson 类,用于解析星汉设备的 JSON 数据
- 在 ReceiverMessageHandler 中集成星汉设备数据的处理逻辑
- 添加 XingHanCommandTypeConstants 常量类,定义星汉设备的命令类型常量
- 实现 XinghanDeviceDataRule 类,处理星汉设备主动上报的数据命令
2025-08-21 17:44:06 +08:00
e6d0e883fb 管理员 2025-08-21 16:51:17 +08:00
5b6927729f WebApp用户信息 2025-08-21 15:17:11 +08:00
bb11bc4dfa WEB端解绑设备 2025-08-20 15:13:43 +08:00
7f65ebedc2 数据字典信息 2025-08-20 13:31:54 +08:00
34ee4cceca web端控制中心 2025-08-19 13:58:48 +08:00
9a6bf05c4b 根据mac地址查询设备详情 2025-08-18 11:04:23 +08:00
b51e88052f 设备分享3 2025-08-16 16:40:58 +08:00
6d9e75d4fa Merge branch '6170' of http://47.107.152.87:3000/dyf/fys-Multi-tenant into 6170 2025-08-16 14:19:19 +08:00
58814fe312 Merge branch 'main' into 6170 2025-08-16 14:18:49 +08:00
6d6db190b9 设备分享2 2025-08-16 11:30:06 +08:00
f8c53451c0 修改灯光上报状态 2025-08-15 18:16:37 +08:00
adc3834ddc Merge branch 'main' into 6170 2025-08-15 10:15:56 +08:00
33f3cb5989 app增加字典 2025-08-15 10:14:35 +08:00
f65a8cdc8c 型号字典 modelDictionary 2025-08-15 09:40:33 +08:00
a21062b296 Merge branch 'main' into 6170 2025-08-15 09:34:17 +08:00
77542f5e76 commit 2025-08-15 09:32:54 +08:00
c587ef7389 解绑优化 2025-08-14 18:57:50 +08:00
48e972166f 型号字典 2025-08-14 18:55:53 +08:00
f1a3a0325b 添加告警处理逻辑6 2025-08-14 18:28:55 +08:00
9e24e3daaf 添加告警处理逻辑4 2025-08-14 17:38:07 +08:00
51741adc69 添加告警处理逻辑3 2025-08-14 16:25:14 +08:00
3145b494d9 添加告警处理逻辑2 2025-08-14 15:56:10 +08:00
a189d0d0f9 添加告警处理逻辑 2025-08-14 15:07:58 +08:00
447aa73ae9 Merge branch 'dyf-device' 2025-08-14 14:22:43 +08:00
9c9d18cddc 查询设备分组列表 2025-08-14 14:21:47 +08:00
8a6c196fb9 访问控制 2025-08-14 11:51:27 +08:00
1af4b165f2 新增设备分组 2025-08-13 19:29:04 +08:00
a8efbb2768 全局控制 2025-08-13 10:40:10 +08:00
546433b3bc 提交2 2025-08-12 18:10:41 +08:00
61ed9f0154 提交 2025-08-12 17:03:11 +08:00
bc165f5d60 分享管理 2025-08-09 17:09:26 +08:00
af64984623 修改分享功能 2025-08-09 08:49:37 +08:00
0c932c686d 修改分享查看 2025-08-08 16:32:40 +08:00
47dbd33d56 修改在线上报状态 2025-08-08 15:09:59 +08:00
72cab138a7 设备控制中心 2025-08-08 10:44:49 +08:00
3abee42b07 设备控制中心 2025-08-08 10:43:53 +08:00
9fb72e5ac0 设备分组 2025-08-08 09:49:08 +08:00
41c6cb935d Merge branch 'dyf-device' 2025-08-07 18:08:12 +08:00
9de55857bc 晶全日志配置 2025-08-07 18:07:04 +08:00
efed6f3683 修改包名 2025-08-07 15:56:12 +08:00
f67e848256 晶全6710 2025-08-07 15:41:57 +08:00
825e9b329c Merge remote-tracking branch 'origin/main' 2025-08-06 10:39:01 +08:00
67764a733e 设备列表电量显示问题,打印日志优化 2025-08-06 10:38:21 +08:00
c2eb5ba524 日志配置 2025-08-06 09:12:47 +08:00
57f074995e 发送设备信息代码实现 2025-08-04 15:35:59 +08:00
6413888a1c Merge branch 'dyf-device' 2025-08-04 09:07:34 +08:00
f4d5f950ce 设备行为 2025-08-04 09:05:10 +08:00
a74b697c0f 设备历史轨迹2 2025-08-02 14:51:06 +08:00
8435a5b0e6 设备行为 2025-08-02 09:18:31 +08:00
ce8f6c9a77 设备历史轨迹 2025-08-02 09:09:02 +08:00
c8dff1a082 位置信息 2025-08-01 17:02:27 +08:00
99355e05b8 Merge branch 'main' into dyf-device 2025-08-01 16:27:53 +08:00
0ad100a7a5 如果经纬度不变就不去调用地图api 2025-08-01 16:27:17 +08:00
8770c217ae 设备日志 2025-08-01 15:19:41 +08:00
6fb8e73535 经纬度bug修复 2025-08-01 14:24:03 +08:00
51d9d7319a app设备列表查询,新增纬度经度 2025-08-01 11:11:36 +08:00
74be5321ec 代码优化2 2025-07-31 19:03:04 +08:00
370783b457 代码优化 2025-07-31 18:09:20 +08:00
8ae15dcd9a 修改用户状态-强制下线 2025-07-31 15:29:37 +08:00
e07dbb01b7 校验设备类型名称 2025-07-31 10:27:02 +08:00
94ac8454ec LngLonUtil 2025-07-31 09:19:06 +08:00
0dc896586d Merge branch 'dyf-device'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/service/AppDeviceBizService.java
#	fys-admin/src/main/java/com/fuyuanshen/global/mqtt/rule/LocationDataRule.java
2025-07-31 09:16:52 +08:00
5a23359112 WEB端解绑设备 2025-07-31 09:08:17 +08:00
ceeda046ea WEB端解绑设备 2025-07-30 18:39:12 +08:00
6827ff0a3c 设备mqtt收发数据2 2025-07-30 17:14:48 +08:00
a119ccc8d6 设备mqtt收发数据 2025-07-30 17:13:57 +08:00
4fa4e5ec29 Merge branch 'main' into dyf-device 2025-07-30 17:07:29 +08:00
ac353b1078 设备mqtt收发数据 2025-07-30 08:50:44 +08:00
abd6d3aa3c 设备日志 2025-07-29 15:22:09 +08:00
984081ac98 设备日志 2025-07-29 11:10:03 +08:00
2b2edf096d 设备下发指令控制 2025-07-28 18:26:02 +08:00
ef39eb7286 地图坐标转换 2025-07-26 16:35:45 +08:00
730e9c0bb7 地图坐标转换 2025-07-26 16:33:28 +08:00
5657c73867 新增设备:蓝牙名称 必填校验 2025-07-26 09:17:21 +08:00
f70c3fa399 Merge branch 'dyf-device' 2025-07-23 19:23:57 +08:00
d849be68ed 删除设备:分配记录 2025-07-23 19:22:25 +08:00
f80debbf2b 登录问题修复 2025-07-23 15:51:25 +08:00
ad59eea2a9 删除设备:分配记录 2025-07-23 14:27:08 +08:00
425 changed files with 34853 additions and 1401 deletions

119
aa.conf Normal file
View File

@ -0,0 +1,119 @@
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name cnxhyc.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
server {
listen 443 ssl http2;
server_name cnxhyc.com;
ssl_certificate /cert/cnxhyc.com.pem;
ssl_certificate_key /cert/cnxhyc.com.key;
# 使用更现代的 SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers TLS_AES_256_GCM_SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location / {
root html;
index index.html index.htm;
}
}
}

View File

@ -123,6 +123,36 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>1.5.7</version>
<scope>compile</scope>
</dependency>
<!-- Java音频转换库 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>3.3.1</version>
</dependency>
<!-- <dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-nativebin-all</artifactId>
<version>3.3.1</version>
</dependency>-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>3.1.1</version>
<scope>compile</scope>
</dependency>
<!-- skywalking 整合 logback -->
<!-- <dependency>-->
<!-- <groupId>org.apache.skywalking</groupId>-->

View File

@ -0,0 +1,96 @@
package com.fuyuanshen;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CorrectVCardGenerator {
public static void main(String[] args) {
// // 定义江西上饶的134号段共22个
// String[] prefixes = {
// "1340703", "1340793", "1342650", "1342651", "1342663",
// "1342664", "1342665", "1343703", "1343793", "1347901",
// "1347902", "1347903", "1347930", "1347931", "1347932",
// "1347933", "1347934", "1347935", "1347936", "1347937",
// "1347938", "1347939"
// }; 1340700 号段(移动)
// 1340708 号段(移动)
// 1340709 号段(移动)
// 1340791 号段(移动)
// 1342668 号段(移动)
// 1343700 号段(移动)
// 1343708 号段(移动)
// 1343709 号段(移动)
// 1343790 号段(移动)
// 1343791 号段(移动)
// 1347910 号段(移动)
// 1347911 号段(移动)
// 1347912 号段(移动)
// 1347913 号段(移动)
// 1347914 号段(移动)
// 1347915 号段(移动)
// 1347916 号段(移动)
// 1347917 号段(移动)
// 1347918 号段(移动)
// 1347919 号段(移动)
// 定义江西南昌的134号段共22个
String[] prefixes = {
"1340700", "1340708", "1340709", "1340791", "1342668",
"1343700", "1343708", "1343709", "1343790", "1343791",
"1347910", "1347911", "1347912", "1347913", "1347914",
"1347915", "1347916", "1347917", "1347918", "1347919"
};
// 创建.vcf文件
String filename = "南昌联系人.vcf";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
// 生成所有联系人
int count = 0;
for (String prefix : prefixes) {
for (int i = 0; i < 100; i++) {
String middle = String.format("%02d", i);
String phoneNumber = prefix + middle + "51";
// 每个联系人以BEGIN:VCARD开始
writer.write("BEGIN:VCARD");
writer.newLine();
writer.write("VERSION:3.0");
writer.newLine();
// 中文姓名(用户+序号)
writer.write("FN:用户" + (count + 1));
writer.newLine();
// 手机号码
writer.write("TEL;TYPE=CELL;TYPE=VOICE:" + phoneNumber);
writer.newLine();
// 添加唯一标识符
writer.write("UID:" + phoneNumber + "@shangrao");
writer.newLine();
// 添加备注信息
writer.write("NOTE:生成于" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
writer.newLine();
// 每个联系人以END:VCARD结束
writer.write("END:VCARD");
writer.newLine();
writer.newLine(); // 联系人之间空一行
count++;
}
}
System.out.println("成功生成 " + count + " 个联系人");
System.out.println("文件已保存为: " + filename);
} catch (IOException e) {
System.err.println("文件写入错误: " + e.getMessage());
}
}
}

View File

@ -1,22 +1,24 @@
package com.fuyuanshen;
package com.fuyuanshen;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 启动程序
*
* @author Lion Li
*/
@SpringBootApplication
public class DromaraApplication {
/**
* 启动程序
*
* @author Lion Li
*/
@SpringBootApplication
@EnableScheduling
public class DromaraApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(DromaraApplication.class);
application.setApplicationStartup(new BufferingApplicationStartup(2048));
application.run(args);
System.out.println("(♥◠‿◠)ノ゙ fys-Vue-Plus启动成功 ლ(´ڡ`ლ)゙");
}
public static void main(String[] args) {
SpringApplication application = new SpringApplication(DromaraApplication.class);
application.setApplicationStartup(new BufferingApplicationStartup(2048));
application.run(args);
System.out.println("(♥◠‿◠)ノ゙ fys-Vue-Plus启动成功 ლ(´ڡ`ლ)゙");
}
}

View File

@ -0,0 +1,81 @@
package com.fuyuanshen;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class SimpleQR {
public static void main(String[] args) throws Exception {
String text = "HELLO";
int size = 21; // 版本1的大小
boolean[][] qr = new boolean[size][size];
// 1. 三个定位标记
for (int i = 0; i < 7; i++)
for (int j = 0; j < 7; j++) {
boolean black = i == 0 || i == 6 || j == 0 || j == 6 || (i > 1 && i < 5 && j > 1 && j < 5);
qr[i][j] = qr[i][size - 1 - j] = qr[size - 1 - i][j] = black;
}
// 2. 定时图案(简化)
for (int i = 8; i < 13; i++) qr[i][6] = qr[6][i] = (i % 2 == 0);
// 3. 编码数据(极简编码)
byte[] data = text.getBytes();
int x = 20, y = 20, up = 1; // 从右下角开始
for (byte b : data)
for (int bit = 7; bit >= 0; bit--) {
while (qr[x][y] || (x == 6 && y < 9) || (y == 6 && x < 9) || (x < 9 && y < 9) ||
(x < 9 && y > size - 10) || (y < 9 && x > size - 10)) {
if (up > 0) {
if (--y < 0) {
y = 0;
x -= 2;
up = -1;
}
} else {
if (++y >= size) {
y = size - 1;
x -= 2;
up = 1;
}
}
if (x == 6) x--;
}
qr[x][y] = ((b >> bit) & 1) == 1;
if (up > 0) {
if (--y < 0) {
y = 0;
x -= 2;
up = -1;
}
} else {
if (++y >= size) {
y = size - 1;
x -= 2;
up = 1;
}
}
if (x == 6) x--;
}
// 4. 保存图像
int scale = 10, margin = 4;
BufferedImage img = new BufferedImage(
size * scale + margin * 2, size * scale + margin * 2, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < img.getWidth(); i++)
for (int j = 0; j < img.getHeight(); j++)
img.setRGB(i, j, 0xFFFFFF); // 白色背景
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (qr[i][j])
for (int di = 0; di < scale; di++)
for (int dj = 0; dj < scale; dj++)
img.setRGB(margin + i * scale + di, margin + j * scale + dj, 0x000000);
ImageIO.write(img, "PNG", new File("qr.png"));
System.out.println("二维码已生成");
}
}

View File

@ -0,0 +1,64 @@
package com.fuyuanshen;
import com.fuyuanshen.equipment.utils.AlibabaTTSUtil;
import com.fuyuanshen.equipment.utils.AudioProcessUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author: 默苍璃
* @date: 2025-12-1518:51
*/
public class Text {
public static void main(String[] args) throws IOException {
String text = "简述人生观的主要内容。\n" +
"人生观的主要内容包括以下三个方面:\n" +
"1.人生目的:回答“人为什么活着”的根本问题。它规定了人生的方向,是人生观的核心。\n" +
"2.人生态度:回答“人应该怎样活着”的问题。它是指人们通过生活实践形成的对人生问题的一种稳定的心理倾向和基本意图。\n" +
"3.人生价值:回答“什么样的人生才有意义”的问题。它是指人的生命及其实践活动对于社会和个人所具有的作用和意义。\n" +
"人生目的、人生态度和人生价值相互联系、相辅相成,共同构成一个有机整体。\n" +
"人生目的是人生观的核心,它决定人生态度和人生价值的方向;人生态度影响人生目的的实现和人生价值的创造;人生价值是衡量人生观正确与否的尺度。";
AlibabaTTSUtil alibabaTTSUtil = new AlibabaTTSUtil();
AudioProcessUtil audioProcessUtil = new AudioProcessUtil();
byte[] rawPcmData = alibabaTTSUtil.generateStandardPcmData(text);
// 使用AudioProcessUtil转换成带头44字节 PCM
byte[] pcmData = audioProcessUtil.rawPcmToStandardWav(rawPcmData);
// String savedPath = audioProcessUtil.saveWavToFile(pcmData, "test_output.wav");
// if (savedPath != null) {
// log.info("测试文件已保存: {}", savedPath);
// }
// 保存WAV文件到本地
String savedPath = saveByteArrayToFile(pcmData, "人生观.wav");
if (savedPath != null) {
System.out.println("WAV文件已保存: " + savedPath);
}
}
private static String saveByteArrayToFile(byte[] data, String filename) throws IOException {
// 确定保存路径(可以是临时目录或指定目录)
String directory = System.getProperty("java.io.tmpdir"); // 使用系统临时目录
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
// 创建完整文件路径
File file = new File(dir, filename);
// 写入文件
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
}
return file.getAbsolutePath();
}
}

View File

@ -4,29 +4,43 @@ import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.fuyuanshen.app.model.AppRegisterBody;
import com.fuyuanshen.app.model.AppSmsLoginBody;
import com.fuyuanshen.app.service.AppLoginService;
import com.fuyuanshen.app.service.AppRegisterService;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.constant.SystemConstants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.domain.model.AppPasswordLoginBody;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.domain.model.SmsLoginBody;
import com.fuyuanshen.common.core.enums.LoginType;
import com.fuyuanshen.common.core.utils.*;
import com.fuyuanshen.common.encrypt.annotation.ApiEncrypt;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.ratelimiter.annotation.RateLimiter;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.system.domain.bo.SysTenantBo;
import com.fuyuanshen.system.domain.vo.SysClientVo;
import com.fuyuanshen.system.domain.vo.SysDictDataVo;
import com.fuyuanshen.system.domain.vo.SysTenantVo;
import com.fuyuanshen.system.service.ISysClientService;
import com.fuyuanshen.system.service.ISysConfigService;
import com.fuyuanshen.system.service.ISysDictTypeService;
import com.fuyuanshen.system.service.ISysTenantService;
import com.fuyuanshen.web.domain.Dto.SystemVersionDto;
import com.fuyuanshen.web.domain.vo.LoginTenantVo;
import com.fuyuanshen.web.domain.vo.LoginVo;
import com.fuyuanshen.web.domain.vo.TenantListVo;
import com.fuyuanshen.web.service.IAuthStrategy;
import com.fuyuanshen.web.service.SysRegisterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
@ -36,8 +50,14 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.net.URL;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import static com.fuyuanshen.common.core.constant.GlobalConstants.DEVICE_SHARE_CODES_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
/**
* APP认证
*
@ -51,8 +71,7 @@ import java.util.List;
public class AppAuthController {
private final AppLoginService loginService;
private final SysRegisterService registerService;
private final ISysConfigService configService;
private final AppRegisterService registerService;
private final ISysTenantService tenantService;
private final ISysClientService clientService;
@ -66,16 +85,34 @@ public class AppAuthController {
@PostMapping("/login")
public R<LoginVo> login(@RequestBody AppSmsLoginBody appSmsLoginBody) {
// SmsLoginBody loginBody = JsonUtils.parseObject(body, SmsLoginBody.class);
ValidatorUtils.validate(appSmsLoginBody);
SmsLoginBody loginBody = new SmsLoginBody();
loginBody.setPhonenumber(appSmsLoginBody.getPhonenumber());
loginBody.setSmsCode(appSmsLoginBody.getSmsCode());
loginBody.setTenantId(appSmsLoginBody.getTenantId());
loginBody.setClientId("ca839698e245d60aa2f0e59bd52b34f8");
loginBody.setGrantType("appSms");
String loginType = appSmsLoginBody.getLoginType();
String body = "";
// 授权类型和客户端id
String clientId = loginBody.getClientId();
String grantType = loginBody.getGrantType();
String clientId = "";
String grantType = "";
String tenantId = appSmsLoginBody.getTenantId();
ValidatorUtils.validate(appSmsLoginBody);
if("2".equals(loginType)){
AppPasswordLoginBody loginBody = new AppPasswordLoginBody();
loginBody.setUsername(appSmsLoginBody.getPhonenumber());
loginBody.setPassword(appSmsLoginBody.getLoginPassword());
loginBody.setClientId("835b15335d389c9fcfdf99421fa8019b");
loginBody.setGrantType("appPassword");
clientId = loginBody.getClientId();
grantType = loginBody.getGrantType();
body = JsonUtils.toJsonString(loginBody);
}else{
SmsLoginBody loginBody = new SmsLoginBody();
loginBody.setPhonenumber(appSmsLoginBody.getPhonenumber());
loginBody.setSmsCode(appSmsLoginBody.getSmsCode());
loginBody.setTenantId(appSmsLoginBody.getTenantId());
loginBody.setClientId("ca839698e245d60aa2f0e59bd52b34f8");
loginBody.setGrantType("appSms");
clientId = loginBody.getClientId();
grantType = loginBody.getGrantType();
body = JsonUtils.toJsonString(loginBody);
}
SysClientVo client = clientService.queryByClientId(clientId);
// 查询不到 client 或 client 内不包含 grantType
if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
@ -85,35 +122,85 @@ public class AppAuthController {
return R.fail(MessageUtils.message("auth.grant.type.blocked"));
}
// 校验租户
loginService.checkTenant(loginBody.getTenantId());
// loginService.checkTenant(loginBody.getTenantId());
loginService.checkTenant(tenantId);
// 登录
String body = JsonUtils.toJsonString(loginBody);
LoginVo loginVo = IAuthStrategy.login(body, client, grantType);
return R.ok(loginVo);
}
/**
* 退出登录
* 用户注销
*/
@PostMapping("/logout")
public R<Void> logout() {
loginService.logout();
return R.ok("退出成功");
@PostMapping("/cancelAccount")
public R<Void> cancelAccount() {
loginService.cancelAccount();
return R.ok("用户注销成功");
}
/**
* 用户注册
*/
@ApiEncrypt
@PostMapping("/register")
public R<Void> register(@Validated @RequestBody RegisterBody user) {
if (!configService.selectRegisterEnabled(user.getTenantId())) {
return R.fail("当前系统没有开启注册功能!");
public R<Void> register(@Validated @RequestBody AppRegisterBody body) {
registerService.register(body);
return R.ok();
}
/**
* 找回密码
*/
@PostMapping("/forgetPassword")
public R<Void> forgetPassword(@Validated @RequestBody AppRegisterBody body) {
registerService.forgetPassword(body);
return R.ok();
}
/**
* 用户注册短信验证码
*
* @param phonenumber 用户手机号
*/
@SaIgnore
@RateLimiter(key = "#phonenumber", time = 60, count = 1)
@GetMapping("/registerSmsCode")
public R<Void> registerSmsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = GlobalConstants.REGISTER_CODE_KEY + phonenumber;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
map.put("code", code);
SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, map);
if (!smsResponse.isSuccess()) {
return R.fail(smsResponse.getData().toString());
}
return R.ok();
}
/**
* 找回密码短信验证码
*
* @param phonenumber 用户手机号
*/
@SaIgnore
@RateLimiter(key = "#phonenumber", time = 60, count = 1)
@GetMapping("/forgetPasswordSmsCode")
public R<Void> forgetPasswordSmsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = GlobalConstants.FORGET_PASSWORD_CODE_KEY + phonenumber;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
map.put("code", code);
SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, map);
if (!smsResponse.isSuccess()) {
return R.fail(smsResponse.getData().toString());
}
registerService.register(user);
return R.ok();
}
@ -170,4 +257,20 @@ public class AppAuthController {
SmsResponse smsResponse = smsBlend.sendMessage("18656573389", "123");
}
/**
* 获取app版本
* @return
*/
@GetMapping("/version")
public R<List<SystemVersionDto>> getAppVersion() {
String versionKey = GLOBAL_REDIS_KEY + "System:Version:Xinghan";
// 缓存告警消息到Redis
String versionJson = RedisUtils.getCacheObject(versionKey);
if (StringUtils.isBlank(versionJson)) { // hutool 工具,可用 StringUtils.isBlank 代替
return R.fail(versionJson);
}
List<SystemVersionDto> list = JSON.parseArray(versionJson, SystemVersionDto.class);
return R.ok(list);
}
}

View File

@ -1,25 +1,24 @@
package com.fuyuanshen.app.controller;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.app.service.AppDeviceBizService;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import jakarta.validation.constraints.NotNull;
import com.fuyuanshen.web.service.device.DeviceBizService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* APP设备信息管理
@ -30,7 +29,7 @@ import java.util.List;
@RequestMapping("/app/device")
public class AppDeviceController extends BaseController {
private final AppDeviceBizService appDeviceService;
private final DeviceBizService appDeviceService;
/**
@ -38,7 +37,6 @@ public class AppDeviceController extends BaseController {
*/
@GetMapping("/list")
public TableDataInfo<AppDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return appDeviceService.queryAppDeviceList(bo,pageQuery);
}
@ -56,7 +54,8 @@ public class AppDeviceController extends BaseController {
*/
@DeleteMapping("/unBind")
public R<Void> unBind(Long id) {
return toAjax(appDeviceService.unBindDevice(id));
Long userId = AppLoginHelper.getUserId();
return toAjax(appDeviceService.unBindDevice(id,userId,0));
}
/**
@ -79,30 +78,19 @@ public class AppDeviceController extends BaseController {
return R.ok("重命名成功!!!");
}
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService.getInfo(id));
@GetMapping("/realTimeStatus")
public R<Map<String, Object>> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
Map<String, Object> status = appDeviceService.getRealTimeStatus(statusDto);
return R.ok(status);
}
/**
* 人员信息登记
* 根据mac查询设备信息
*/
@PostMapping(value = "/registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService.registerPersonInfo(bo));
@GetMapping("/getDeviceInfoByDeviceMac")
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
}
/**
* 发送信息
*/
@PostMapping(value = "/sendMessage")
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendMessage(bo));
}
}

View File

@ -16,6 +16,7 @@ import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.ratelimiter.annotation.RateLimiter;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.web.service.DeviceShareService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
@ -43,16 +44,15 @@ import static com.fuyuanshen.common.core.constant.GlobalConstants.DEVICE_SHARE_C
@RequestMapping("/app/deviceShare")
public class AppDeviceShareController extends BaseController {
private final IAppDeviceShareService deviceShareService;
private final AppDeviceShareService appDeviceShareService;
/**
* 分享管理列表
*/
@GetMapping("/deviceShareList")
public TableDataInfo<AppDeviceShareVo> list(AppDeviceShareBo bo, PageQuery pageQuery) {
return deviceShareService.queryPageList(bo, pageQuery);
return appDeviceShareService.queryPageList(bo, pageQuery);
}
/**
@ -60,7 +60,7 @@ public class AppDeviceShareController extends BaseController {
*/
@GetMapping("/otherDeviceShareList")
public TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery) {
return deviceShareService.otherDeviceShareList(bo, pageQuery);
return appDeviceShareService.otherDeviceShareList(bo, pageQuery);
}
/**
@ -94,6 +94,7 @@ public class AppDeviceShareController extends BaseController {
return toAjax(appDeviceShareService.remove(ids));
}
/**
* 短信验证码
*
@ -115,4 +116,5 @@ public class AppDeviceShareController extends BaseController {
}
return R.ok();
}
}

View File

@ -11,6 +11,7 @@ import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
/**
@ -25,6 +26,7 @@ public class AppFileController extends BaseController {
private final AppFileService appFileService;
/**
* 查询文件列表
*/
@ -33,11 +35,12 @@ public class AppFileController extends BaseController {
return R.ok(appFileService.list(bo));
}
/**
* 上传文件
*/
@PostMapping("/upload")
public R<Void> upload(@Validated @ModelAttribute AppFileDto bo) {
public R<Void> upload(@Validated @ModelAttribute AppFileDto bo) throws IOException {
return toAjax(appFileService.add(bo));
}
@ -52,4 +55,5 @@ public class AppFileController extends BaseController {
}
return toAjax(appFileService.delete(ids));
}
}

View File

@ -25,6 +25,7 @@ public class AppOperationVideoController extends BaseController {
private final IAppOperationVideoService appOperationVideoService;
/**
* 查询操作视频列表
*/
@ -68,4 +69,5 @@ public class AppOperationVideoController extends BaseController {
public R<Void> deleteOperationVideo(@PathVariable Long id) {
return toAjax(appOperationVideoService.deleteWithValidByIds(List.of(id), true));
}
}

View File

@ -0,0 +1,55 @@
package com.fuyuanshen.app.controller;
import com.fuyuanshen.app.model.AppRegisterBody;
import com.fuyuanshen.app.model.AppUpdatePasswordBody;
import com.fuyuanshen.app.service.AppLoginService;
import com.fuyuanshen.app.service.AppRegisterService;
import com.fuyuanshen.common.core.domain.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* APP我的
*
*/
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/userCenter")
public class AppUserCenterController {
private final AppLoginService loginService;
private final AppRegisterService registerService;
/**
* 用户注销
*/
@PostMapping("/cancelAccount")
public R<Void> cancelAccount() {
loginService.cancelAccount();
return R.ok("用户注销成功");
}
/**
* 修改密码
*/
@PostMapping("/updatePassword")
public R<Void> updatePassword(@Validated @RequestBody AppUpdatePasswordBody body) {
registerService.updatePassword(body);
return R.ok();
}
/**
* 退出登录
*/
@PostMapping("/logout")
public R<Void> logout() {
loginService.logout();
return R.ok("退出成功");
}
}

View File

@ -0,0 +1,140 @@
package com.fuyuanshen.app.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import com.fuyuanshen.app.domain.bo.AppBusinessFileBo;
import com.fuyuanshen.app.domain.dto.AppAudioFileDto;
import com.fuyuanshen.app.domain.dto.AppFileDto;
import com.fuyuanshen.app.domain.dto.AppFileRenameDto;
import com.fuyuanshen.app.domain.dto.TextToSpeechRequest;
import com.fuyuanshen.app.domain.vo.AppFileVo;
import com.fuyuanshen.app.service.AudioProcessService;
import com.fuyuanshen.app.service.VideoProcessService;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.idempotent.annotation.RepeatSubmit;
import com.fuyuanshen.common.web.core.BaseController;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* APP 视频处理控制器
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/video")
public class AppVideoController extends BaseController {
private final VideoProcessService videoProcessService;
private final AudioProcessService audioProcessService;
/**
* 上传视频转码code默认1RGB565 2BGR565
*/
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
public R<List<String>> uploadVideo(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "1") int code) {
return R.ok(videoProcessService.processVideo(file, code));
}
/**
* 上传音频文件并转码
*/
@PostMapping(value = "/audio", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
public R<List<String>> uploadAudio(@RequestParam("file") MultipartFile file) {
return R.ok(audioProcessService.processAudio(file));
}
/**
* 文字转音频TTS服务
*/
@GetMapping("/audioTTS")
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
public R<List<String>> uploadAudioTTS(@RequestParam String text) throws IOException {
return R.ok(audioProcessService.generateStandardPcmData(text));
}
/**
* 提取文本内容只支持txt/docx
*/
@PostMapping(value = "/extract", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
public R<String> extract(@RequestParam("file") MultipartFile file) throws Exception {
return R.ok("Success",audioProcessService.extract(file));
}
/**
* 上传音频文件进行处理
* 支持MP3、WAV、PCM格式
*/
@PostMapping("/uploadAudioToOss")
public R<String> uploadAudioToOss(@ModelAttribute AppAudioFileDto bo) {
try {
String result = audioProcessService.uploadAudioToOss(bo);
return R.ok(result);
} catch (IllegalArgumentException e) {
return R.fail("文件格式错误: " + e.getMessage());
} catch (Exception e) {
return R.fail("上传处理失败: " + e.getMessage());
}
}
/**
* 文本转语音
* 支持MP3、WAV、PCM格式
*/
@PostMapping("/ttsToOss")
public R<String> textToSpeech(@RequestBody TextToSpeechRequest request) {
try {
if (request.getDeviceId() == null) {
return R.fail("设备ID不能为空");
}
String result = audioProcessService.textToSpeech(
request.getDeviceId(),
request.getText(),
request.getFileSuffix()
);
return R.ok(result);
} catch (Exception e) {
return R.fail("文本转语音失败: " + e.getMessage());
}
}
/**
* 查询语音文件列表
*/
@GetMapping("/queryAudioFileList")
public R<List<AppFileVo>> queryAudioFileList(Long deviceId) {
return R.ok(audioProcessService.queryAudioFileList(deviceId));
}
/**
* 删除语音文件
*/
@GetMapping("/deleteAudioFile")
public R<Void> deleteAudioFile(Long fileId,Long deviceId) {
return audioProcessService.deleteAudioFile(fileId,deviceId);
}
/**
* 文件重命名
*/
@PostMapping("/renameAudioFile")
public R<Void> renameAudioFile(@RequestBody AppFileRenameDto bo) {
return audioProcessService.renameAudioFile(bo);
}
}

View File

@ -0,0 +1,124 @@
package com.fuyuanshen.app.controller.device;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQBizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* BJQ6170设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/bjq/device")
public class AppDeviceBJQController extends BaseController {
private final DeviceBJQBizService appDeviceService;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService.getInfo(id));
}
/**
* 人员信息登记
*/
@PostMapping(value = "/registerPersonInfo")
// @FunctionAccessAnnotation("registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService.registerPersonInfo(bo));
}
/**
* 发送信息
*/
@PostMapping(value = "/sendMessage")
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendMessage(bo));
}
/**
* 发送报警信息
*/
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if(file.getSize()>1024*1024*2){
return R.warn("图片不能大于2M");
}
appDeviceService.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 灯光模式
* 0关灯1强光模式2弱光模式, 3爆闪模式, 4泛光模式
*/
// @FunctionAccessAnnotation("lightModeSettings")
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置
*
*/
// @FunctionAccessAnnotation("lightBrightnessSettings")
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置
*
*/
@PostMapping("/laserModeSettings")
// @FunctionAccessAnnotation("laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.laserModeSettings(params);
return R.ok();
}
}

View File

@ -0,0 +1,120 @@
package com.fuyuanshen.app.controller.device;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQBizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* HBY210设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/hby/device")
public class AppDeviceHBYController extends BaseController {
private final DeviceBJQBizService appDeviceService;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService.getInfo(id));
}
/**
* 人员信息登记
*/
@PostMapping(value = "/registerPersonInfo")
// @FunctionAccessAnnotation("registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService.registerPersonInfo(bo));
}
/**
* 发送信息
*/
@PostMapping(value = "/sendMessage")
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendMessage(bo));
}
/**
* 发送报警信息
*/
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if(file.getSize()>1024*1024*2){
return R.warn("图片不能大于2M");
}
appDeviceService.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 灯光模式
* 0关灯1强光模式2弱光模式, 3爆闪模式, 4泛光模式
*/
// @FunctionAccessAnnotation("lightModeSettings")
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置
*
*/
// @FunctionAccessAnnotation("lightBrightnessSettings")
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置
*
*/
@PostMapping("/laserModeSettings")
// @FunctionAccessAnnotation("laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.laserModeSettings(params);
return R.ok();
}
}

View File

@ -0,0 +1,170 @@
package com.fuyuanshen.app.controller.device;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.log.annotation.Log;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.customer.mapper.CustomerMapper;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.service.DeviceTypeService;
import com.fuyuanshen.web.domain.Dto.DeviceXinghanInstructDto;
import com.fuyuanshen.web.service.device.DeviceBJQBizService;
import com.fuyuanshen.web.service.device.DeviceXinghanBizService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* HBY670设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/xinghan/device")
public class AppDeviceXinghanController extends BaseController {
private final DeviceXinghanBizService appDeviceService;
private final DeviceService deviceService;
/**
* 人员信息登记
*/
@Log(title = "xinghan指令-人员信息登记")
@PostMapping(value = "/registerPersonInfo")
// @FunctionAccessAnnotation("registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService.registerPersonInfo(bo));
}
/**
* 发送紧急通知
*/
@Log(title = "xinghan指令-发送紧急通知")
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片
*/
@Log(title = "xinghan指令-上传设备logo图片")
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if (file.getSize() > 1024 * 1024 * 2) {
return R.warn("图片不能大于2M");
}
appDeviceService.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 静电预警档位
* 3,2,1,0,分别表示高档/中档/低挡/关闭
*/
@Log(title = "xinghan指令-静电预警档位")
@PostMapping("/DetectGradeSettings")
public R<Void> DetectGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
// params 转 JSONObject
appDeviceService.upDetectGradeSettings(params);
return R.ok();
}
/**
* 照明档位
* 照明档位2,1,0,分别表示弱光/强光/关闭
*/
@Log(title = "xinghan指令-照明档位")
@PostMapping("/LightGradeSettings")
public R<Void> LightGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
// params 转 JSONObject
appDeviceService.upLightGradeSettings(params);
return R.ok();
}
/**
* SOS档位s
* SOS档位2,1,0, 分别表示红蓝模式/爆闪模式/关闭
*/
@Log(title = "xinghan指令-SOS档位s")
@PostMapping("/SOSGradeSettings")
public R<Void> SOSGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
// params 转 JSONObject
appDeviceService.upSOSGradeSettings(params);
return R.ok();
}
/**
* 静止报警状态
* 静止报警状态0-未静止报警1-正在静止报警。
*/
@Log(title = "xinghan指令-静止报警状态")
@PostMapping("/ShakeBitSettings")
public R<Void> ShakeBitSettings(@RequestBody DeviceXinghanInstructDto params) {
// params 转 JSONObject
appDeviceService.upShakeBitSettings(params);
return R.ok();
}
@GetMapping(value = "/typeAll")
@Operation(summary = "查询所有设备类型")
public R<List<DeviceType>> queryDeviceTypes() {
List<DeviceType> deviceTypes = appDeviceService.queryDeviceTypes();
return R.ok(deviceTypes);
}
// @Log("新增设备")
@Log(title = "新增设备")
@PostMapping(value = "/add")
public R<Void> addDevice(@RequestBody DeviceForm deviceForm) {
try {
appDeviceService.addDevice(deviceForm);
} catch (Exception e) {
return R.fail(e.getMessage());
}
return R.ok();
}
@PostMapping(value = "/GetDeviceByName")
@Operation(summary = "通过蓝牙名/设备名称查询设备")
public R<Object> GetDeviceByName(@RequestBody DeviceForm deviceForm) {
Object device = appDeviceService.GetDeviceByName(deviceForm);
return R.ok(device);
}
@PostMapping(value = "/getEquipCountByType")
@Operation(summary = "查询某个类型下的设备总数量")
public R<Object> getEquipCountByType(@RequestBody DeviceForm deviceForm) {
Object device = appDeviceService.getEquipCountByType(deviceForm);
return R.ok(device);
}
@PostMapping(value = "/getEquipAllByType")
@Operation(summary = "查询某个类型下的设备")
public R<List<Map<String,Object>>> getEquipAllByType(@RequestBody DeviceForm deviceForm){
List<Map<String,Object>> list=appDeviceService.getEquipAllByType(deviceForm);
return R.ok(list);
}
}

View File

@ -0,0 +1,48 @@
package com.fuyuanshen.app.controller.device;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQBizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* BJQ6170设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/test")
public class TestController extends BaseController {
private final DeviceBJQBizService appDeviceService;
/**
* 上传设备logo图片
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if(file.getSize()>1024*1024*2){
return R.warn("图片不能大于2M");
}
appDeviceService.uploadDeviceLogo2(bo);
return R.ok();
}
}

View File

@ -0,0 +1,156 @@
package com.fuyuanshen.app.controller.device.bjq;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* BJQ6075 设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/bjq6075/device")
public class AppDeviceBJQ6075Controller extends BaseController {
private final DeviceBJQ6075BizService appDeviceService6075;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
/**
* 人员信息登记 1
*/
@PostMapping(value = "/registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService6075.registerPersonInfo(bo));
}
/**
* 发送信息 2
*/
@PostMapping(value = "/sendMessage")
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendMessage(bo));
}
/**
* 发送报警信息 3
*/
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片 4
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if (file.getSize() > 1024 * 1024 * 2) {
return R.warn("图片不能大于2M");
}
appDeviceService6075.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 灯光模式 5
* (主光模式)
* 0关闭灯光1强光2超强光, 3工作光, 4节能光5爆闪6SOS
*/
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光模式 6
* (辅光模式)
* 0关闭灯光1泛光2泛光爆闪, 3警示灯, 4警示灯/泛光)
*/
@PostMapping("/auxiliaryLightModeSettings")
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置 7
*/
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置 8
*/
@PostMapping("/laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 声光报警模式设置 9
* Sound and light alarm
*/
@PostMapping("/salaModeSettings")
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 获取设备分享详细信息
*
* @param id 主键
*/
@GetMapping("/getShareInfo/{id}")
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
}

View File

@ -0,0 +1,155 @@
package com.fuyuanshen.app.controller.device.bjq;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* BJQ6331便携式工作灯
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/BJQ6331/device")
public class AppDeviceBJQ6331Controller extends BaseController {
private final DeviceBJQ6075BizService appDeviceService6075;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
/**
* 人员信息登记 1
*/
@PostMapping(value = "/registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService6075.registerPersonInfo(bo));
}
/**
* 发送信息 2
*/
@PostMapping(value = "/sendMessage")
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendMessage(bo));
}
/**
* 发送报警信息 3
*/
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片 4
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if (file.getSize() > 1024 * 1024 * 2) {
return R.warn("图片不能大于2M");
}
appDeviceService6075.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 灯光模式 5
* (主光模式)
* 0关闭灯光1强光2超强光, 3工作光, 4节能光5爆闪6SOS
*/
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光模式 6
* (辅光模式)
* 0关闭灯光1泛光2泛光爆闪, 3警示灯, 4警示灯/泛光)
*/
@PostMapping("/auxiliaryLightModeSettings")
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置 7
*/
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置 8
*/
@PostMapping("/laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 声光报警模式设置 9
* Sound and light alarm
*/
@PostMapping("/salaModeSettings")
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 获取设备分享详细信息
*
* @param id 主键
*/
@GetMapping("/getShareInfo/{id}")
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
}

View File

@ -0,0 +1,191 @@
package com.fuyuanshen.app.controller.device.bjq;
import com.fuyuanshen.app.domain.vo.AppDeviceHBY100JDetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.web.service.device.DeviceHBY100JBizService;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* HBY100J设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/hby100j/device")
public class AppDeviceHBY100JController extends BaseController {
private final DeviceHBY100JBizService deviceHBY100JBizService;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDeviceHBY100JDetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(deviceHBY100JBizService.getInfo(id));
}
/**
* 更新语音
*/
@PostMapping("/updateVoice")
public R<Void> updateVoice(@RequestBody HBY100JUpdateVoiceDto dto) {
deviceHBY100JBizService.updateVoice(dto);
return R.ok();
}
/**
* 强制报警
*
*/
@PostMapping("/forceAlarmActivation")
public R<Void> forceAlarmActivation(@RequestBody HBY100JForceAlarmActivationDto bo) {
deviceHBY100JBizService.forceAlarmActivation(bo);
return R.ok();
}
/**
* 爆闪模式
*/
@PostMapping("/strobeMode")
public R<Void> strobeMode(@RequestBody HBY100JStrobeModeDto params) {
deviceHBY100JBizService.strobeMode(params);
return R.ok();
}
/**
* 灯光调节
*/
@PostMapping("/lightAdjustment")
public R<Void> lightAdjustment(@RequestBody HBY100JLightAdjustmentDto params) {
deviceHBY100JBizService.lightAdjustment(params);
return R.ok();
}
/**
* 爆闪频率
*/
@PostMapping("/strobeFrequency")
public R<Void> strobeFrequency(@RequestBody HBY100JStrobeFrequencyDto params) {
deviceHBY100JBizService.strobeFrequency(params);
return R.ok();
}
/**
* 修改音量
*/
@PostMapping("/updateVolume")
public R<Void> updateVolume(@RequestBody HBY100JUpdateVolumeDto params) {
deviceHBY100JBizService.updateVolume(params);
return R.ok();
}
@Data
public static class HBY100JUpdateVoiceDto {
private Long id;
}
@Data
public static class HBY100JForceAlarmActivationDto {
/**
* 设备ID
*/
List<Long> deviceIds;
/**
* 0 关闭, 1开启
*/
private Integer voiceStrobeAlarm;
/**
* 0 公安,1消防,2应急,3交警4 市政5 铁路6 医疗7部队8 水利,9 语音
*/
private Integer mode;
}
@Data
public static class HBY100JUpdateVolumeDto{
/**
* 设备ID
*/
private Long deviceId;
/**
* "volume": 1-100(app端可根据需求把40作为低音量, 70作为中音量100作为高音量)
*/
private Integer volume;
}
@Data
public static class HBY100JStrobeFrequencyDto{
/**
* 设备ID
*/
private Long deviceId;
/**
* "frequency": 1-12
*/
private Integer frequency;
}
@Data
public static class HBY100JLightAdjustmentDto{
/**
* 设备ID
*/
private Long deviceId;
/**
* 亮度值0-100
*/
private Integer brightness;
// /**
// * 红色LED亮度值0-100
// */
// private Integer red;
//
// /**
// * 蓝色LED亮度值0-100
// */
// private Integer blue;
//
// /**
// * 黄色LED亮度值0-100
// */
// private Integer yellow;
}
@Data
public static class HBY100JStrobeModeDto{
/**
* 设备ID
*/
private Long deviceId;
/**
* 0 关闭 1 开启
*/
private Integer enable;
/**
* 0 红色爆闪1 蓝色爆闪2 黄色爆闪3红色顺时针旋转爆闪4黄色顺时针旋转爆闪5红蓝顺时针旋转爆闪6 红蓝交替爆闪
*/
private Integer mode;
}
}

View File

@ -0,0 +1,156 @@
package com.fuyuanshen.app.controller.device.bjq;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* HBY335LED救生照明线
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/HBY335/device")
public class AppDeviceHBY335Controller extends BaseController {
private final DeviceBJQ6075BizService appDeviceService6075;
/**
* 获取设备详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
/**
* 人员信息登记 1
*/
@PostMapping(value = "/registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService6075.registerPersonInfo(bo));
}
/**
* 发送信息 2
*/
@PostMapping(value = "/sendMessage")
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendMessage(bo));
}
/**
* 发送报警信息 3
*/
@PostMapping(value = "/sendAlarmMessage")
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
}
/**
* 上传设备logo图片 4
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if (file.getSize() > 1024 * 1024 * 2) {
return R.warn("图片不能大于2M");
}
appDeviceService6075.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 灯光模式 5
* (主光模式)
* 0关闭灯光1强光2超强光, 3工作光, 4节能光5爆闪6SOS
*/
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光模式 6
* (辅光模式)
* 0关闭灯光1泛光2泛光爆闪, 3警示灯, 4警示灯/泛光)
*/
@PostMapping("/auxiliaryLightModeSettings")
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置 7
*/
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置 8
*/
@PostMapping("/laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 声光报警模式设置 9
* Sound and light alarm
*/
@PostMapping("/salaModeSettings")
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService6075.laserModeSettings(params);
return R.ok();
}
/**
* 获取设备分享详细信息
*
* @param id 主键
*/
@GetMapping("/getShareInfo/{id}")
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceService6075.getInfo(id));
}
}

View File

@ -0,0 +1,17 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
@Data
public class AppAudioFileDto {
private Long deviceId;
/**
* 文件
*/
private MultipartFile file;
}

View File

@ -0,0 +1,30 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Data
public class AppDeviceLogoUploadDto {
private Long deviceId;
private String deviceImei;
/**
* 文件
*/
private MultipartFile file;
// /**
// * 文件
// */
// private List<MultipartFile> files;
private List<Long> deviceIds;
private Integer chunkSize;
}

View File

@ -18,4 +18,9 @@ public class AppFileDto {
*/
private MultipartFile[] files;
/**
* 多设备id
*/
private Long[] deviceIds;
}

View File

@ -0,0 +1,24 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
@Data
public class AppFileRenameDto {
/**
* 文件id
*/
private Long fileId;
/**
* 设备id
*/
private Long deviceId;
/**
* 文件名称
*/
private String fileName;
}

View File

@ -0,0 +1,13 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
@Data
public class AppLightModeDto {
private Long deviceId;
//0关灯1强光模式2弱光模式, 3爆闪模式, 4泛光模式
private Integer mode;
}

View File

@ -0,0 +1,30 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
/**
* 设备实时状态
*/
@Data
public class AppRealTimeStatusDto {
/**
* 设备IMEI
*/
private String deviceImei;
/**
* 获取实时状态类型FunctionAccessBatchStatusRule 批量 FunctionAccessStatusRule 单个
*/
private String typeName;
/**
* 功能类型
*/
private String functionMode;
/**
* 批次号
*/
private String batchId;
}

View File

@ -0,0 +1,22 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
@Data
public class DeviceInstructDto {
private Long deviceId;
private String deviceImei;
/**
* 下发指令
*/
private String instructValue;
/**
* 下发指令类型
*/
private String instructType;
}

View File

@ -0,0 +1,11 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
/**
* PCM生成请求实体
*/
@Data
public class PcmGenerationRequest {
private String text;
}

View File

@ -0,0 +1,19 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
/**
* 文本转语音请求实体
*/
@Data
public class TextToSpeechRequest {
private Long deviceId;
private String text;
/**
* 文件后缀格式
*/
private String fileSuffix;
}

View File

@ -0,0 +1,130 @@
package com.fuyuanshen.app.http;
import com.alibaba.nls.client.AccessToken;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static cn.dev33.satoken.SaManager.log;
public class HttpTtsClient {
private String accessKeyId;
private String accessKeySecret;
private String appKey;
/**
* 阿里云TTS服务基础URL
*/
private static final String BASE_URL = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts";
public HttpTtsClient(String accessKeyId, String accessKeySecret, String appKey) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.appKey = appKey;
}
private String refreshAccessToken() {
try {
// 调用阿里云API获取访问令牌
AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
accessToken.apply();
String token = accessToken.getToken();
log.info("访问令牌刷新成功");
return token;
} catch (Exception e) {
log.error("刷新访问令牌失败: {}", e.getMessage(), e);
return null;
}
}
/**
* 使用HTTP POST方式调用阿里云TTS服务生成MP3格式语音
*/
public byte[] synthesizeTextToMp3(String text) throws IOException {
String endpoint = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts";
// 构建请求体
// String requestBody = String.format(
// "{\"appkey\":\"%s\",\"text\":\"%s\",\"voice\":\"zhifeng\",\"format\":\"MP3\",\"sample_rate\":24000,\"volume\":50,\"speech_rate\":0,\"pitch_rate\":0}",
// appKey,
// text.replace("\"", "\\\"")
// );
String token = refreshAccessToken();
String requestBody = " {\n" +
" \"appkey\":\""+appKey+"\",\n" +
" \"text\":\""+text+"\",\n" +
" \"token\":\""+token+"\",\n" +
" \"format\":\"mp3\"\n" +
" }";
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法和头部
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", buildAuthorization());
conn.setRequestProperty("Content-Length", String.valueOf(requestBody.getBytes().length));
conn.setDoOutput(true);
// 发送请求体
try (OutputStream os = conn.getOutputStream()) {
os.write(requestBody.getBytes("UTF-8"));
}
// 读取响应
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取音频数据
try (InputStream is = conn.getInputStream()) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
} else {
throw new IOException("HTTP请求失败状态码: " + responseCode);
}
}
/**
* 构建授权头部
*/
private String buildAuthorization() {
// 实际实现需要根据阿里云API规范构建签名
// 这里是简化示例
return "Bearer " + generateAccessToken();
}
/**
* 生成访问令牌
*/
private String generateAccessToken() {
// 实际实现需要调用阿里云获取token的API
return "your-access-token";
}
/**
* 保存MP3到文件
*/
public String saveMp3ToFile(String text, String outputPath) throws IOException {
byte[] mp3Data = synthesizeTextToMp3(text);
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
fos.write(mp3Data);
}
return outputPath;
}
}

View File

@ -0,0 +1,32 @@
package com.fuyuanshen.app.http;
import java.io.IOException;
public class HttpTtsExample {
/**
* appKey: lbGuq5K5bEH4uxmT
* akId: LTAI5t66moCkhNC32TDJ5ReP
* akSecret: 2F3sdoBJ08bYvJcuDgSkLnJwGXsvYH
* @param args
*/
public static void main(String[] args) {
String accessKeyId = "LTAI5t66moCkhNC32TDJ5ReP";
String accessKeySecret = "2F3sdoBJ08bYvJcuDgSkLnJwGXsvYH";
String appKey = "lbGuq5K5bEH4uxmT";
try {
// 使用HTTP方式调用
HttpTtsClient httpClient = new HttpTtsClient(accessKeyId, accessKeySecret, appKey);
String text = "大江东去,浪淘尽,千古风流人物。故垒西边,人道是,三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。";
String outputPath = "D:\\http_output9.mp3";
String resultFile = httpClient.saveMp3ToFile(text, outputPath);
System.out.println("MP3音频已保存至: " + resultFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,58 @@
package com.fuyuanshen.app.http;
import okhttp3.*;
import java.io.IOException;
public class OkHttpTtsClient {
private OkHttpClient client = new OkHttpClient();
private String accessKeyId;
private String accessKeySecret;
private String appKey;
public OkHttpTtsClient(String accessKeyId, String accessKeySecret, String appKey) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.appKey = appKey;
}
/**
* 使用OkHttp调用TTS服务
*/
public byte[] synthesizeTextToMp3(String text) throws IOException {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String jsonPayload = String.format(
"{\"appkey\":\"%s\",\"text\":\"%s\",\"voice\":\"zhifeng\",\"format\":\"MP3\",\"sample_rate\":24000,\"volume\":50,\"speech_rate\":0,\"pitch_rate\":0}",
appKey,
text.replace("\"", "\\\"")
);
RequestBody body = RequestBody.create(JSON,jsonPayload);
Request request = new Request.Builder()
.url("https://nls-gateway.cn-shanghai.aliyuncs.com/v1/tts")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + getAccessToken())
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("HTTP请求失败: " + response.code());
}
ResponseBody responseBody = response.body();
if (responseBody != null) {
return responseBody.bytes();
} else {
throw new IOException("响应体为空");
}
}
}
private String getAccessToken() {
// 实现获取访问令牌的逻辑
return "your-access-token";
}
}

View File

@ -0,0 +1,48 @@
package com.fuyuanshen.app.http;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 获取阿里云TTS服务访问令牌
*/
public class TokenClient {
public static String getAccessToken(String accessKeyId, String accessKeySecret) throws IOException {
String endpoint = "https://nls-meta.cn-shanghai.aliyuncs.com/v1/token";
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
// 发送认证信息
String params = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s",
accessKeyId, accessKeySecret);
try (OutputStream os = conn.getOutputStream()) {
os.write(params.getBytes("UTF-8"));
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 解析响应获取token实际需要使用JSON解析库
return response.toString().replaceAll(".*\"access_token\":\"([^\"]+)\".*", "$1");
}
} else {
throw new IOException("获取令牌失败,状态码: " + responseCode);
}
}
}

View File

@ -0,0 +1,30 @@
package com.fuyuanshen.app.model;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class AppRegisterBody {
/**
* 手机号
*/
@NotBlank(message = "{user.phonenumber.not.blank}")
private String phonenumber;
/**
* 短信code
*/
private String smsCode;
/**
* 租户ID
*/
@NotBlank(message = "租户ID不能为空")
private String tenantId;
/**
* 登录密码
*/
private String password;
}

View File

@ -14,7 +14,6 @@ public class AppSmsLoginBody {
/**
* 短信code
*/
@NotBlank(message = "{sms.code.not.blank}")
private String smsCode;
/**
@ -23,4 +22,14 @@ public class AppSmsLoginBody {
@NotBlank(message = "租户ID不能为空")
private String tenantId;
/**
* 登录方式 1:手机验证码登录 2:密码登录
*/
@NotBlank(message = "登录方式不能为空")
private String loginType;
/**
* 登录密码
*/
private String loginPassword;
}

View File

@ -0,0 +1,12 @@
package com.fuyuanshen.app.model;
import lombok.Data;
@Data
public class AppUpdatePasswordBody {
/**
* 登录密码
*/
private String password;
}

View File

@ -1,237 +0,0 @@
package com.fuyuanshen.app.service;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.core.utils.ObjectUtils;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.utils.c.ReliableTextToBitmap;
import com.fuyuanshen.system.mqtt.config.MqttGateway;
import com.fuyuanshen.system.mqtt.constants.MqttConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class AppDeviceBizService {
private final APPDeviceMapper appDeviceMapper;
private final DeviceMapper deviceMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final MqttGateway mqttGateway;
public List<APPDeviceTypeVo> getTypeList() {
Long userId = AppLoginHelper.getUserId();
return appDeviceMapper.getTypeList(userId);
}
public void reName(APPReNameDTO reNameDTO) {
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", reNameDTO.getId())
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("device_name", reNameDTO.getDeviceName());
deviceMapper.update(updateWrapper);
}
public int sendMessage(AppDeviceSendMsgBo bo) {
List<Long> deviceIds = bo.getDeviceIds();
if(deviceIds == null || deviceIds.isEmpty()){
throw new ServiceException("请选择设备");
}
for (Long deviceId : deviceIds){
Device deviceObj = deviceMapper.selectById(deviceId);
if(deviceObj==null) {
throw new ServiceException("设备不存在"+deviceId);
}
byte[] msg = ReliableTextToBitmap.textToBitmapBytes(bo.getSendMsg());
Map<String,Object> linkHashMap = new HashMap<>();
linkHashMap.put("message",msg);
String sendMsg = JSON.toJSONString(linkHashMap);
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY+deviceObj.getDeviceImei(), 1 ,sendMsg);
log.info("发送设备消息:{}", bo.getSendMsg());
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", deviceId)
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("send_msg", bo.getSendMsg());
deviceMapper.update(updateWrapper);
}
return 1;
}
public TableDataInfo<AppDeviceVo> queryAppDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery) {
if (bo.getBindingUserId() == null) {
Long userId = AppLoginHelper.getUserId();
bo.setBindingUserId(userId);
}
Page<AppDeviceVo> result = deviceMapper.queryAppBindDeviceList(pageQuery.build(), bo);
return TableDataInfo.build(result);
}
public int bindDevice(AppDeviceBo bo) {
Integer mode = bo.getCommunicationMode();
Long userId = AppLoginHelper.getUserId();
if (mode == CommunicationModeEnum.FOUR_G.getValue()) {
String deviceImei = bo.getDeviceImei();
QueryWrapper<Device> qw = new QueryWrapper<Device>()
.eq("device_imei", deviceImei);
List<Device> devices = deviceMapper.selectList(qw);
if (devices.isEmpty()) {
throw new RuntimeException("请先将设备入库!!!");
}
Device device = devices.get(0);
if (device.getBindingStatus() != null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()) {
throw new RuntimeException("设备已绑定");
}
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.BOUND.getCode())
.set("binding_user_id", userId)
.set("binding_time", new Date());
return deviceMapper.update(null, deviceUpdateWrapper);
} else if (mode == CommunicationModeEnum.BLUETOOTH.getValue()) {
String deviceMac = bo.getDeviceMac();
QueryWrapper<Device> qw = new QueryWrapper<Device>()
.eq("device_mac", deviceMac);
List<Device> devices = deviceMapper.selectList(qw);
if (devices.isEmpty()) {
throw new RuntimeException("请先将设备入库!!!");
}
Device device = devices.get(0);
if (device.getBindingStatus() != null && device.getBindingStatus() == BindingStatusEnum.BOUND.getCode()) {
throw new RuntimeException("设备已绑定");
}
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.BOUND.getCode())
.set("binding_user_id", userId)
.set("binding_time", new Date());
return deviceMapper.update(null, deviceUpdateWrapper);
} else {
throw new RuntimeException("通讯方式错误");
}
}
public int unBindDevice(Long id) {
Device device = deviceMapper.selectById(id);
if (device == null) {
throw new RuntimeException("请先将设备入库!!!");
}
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId())
.set("binding_status", BindingStatusEnum.UNBOUND.getCode())
.set("binding_user_id", null)
.set("binding_time", null);
return deviceMapper.update(null, deviceUpdateWrapper);
}
public AppDeviceDetailVo getInfo(Long id) {
Device device = deviceMapper.selectById(id);
if (device == null) {
throw new RuntimeException("请先将设备入库!!!");
}
AppDeviceDetailVo vo = new AppDeviceDetailVo();
vo.setDeviceId(device.getId());
vo.setDeviceName(device.getDeviceName());
vo.setDevicePic(device.getDevicePic());
vo.setDeviceImei(device.getDeviceImei());
vo.setDeviceMac(device.getDeviceMac());
vo.setDeviceStatus(device.getDeviceStatus());
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
if(deviceType!=null){
vo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
vo.setTypeName(deviceType.getTypeName());
}
vo.setBluetoothName(device.getBluetoothName());
vo.setSendMsg(device.getSendMsg());
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
.eq("device_id", device.getId());
AppPersonnelInfo appPersonnelInfo = appPersonnelInfoMapper.selectOne(qw);
if(appPersonnelInfo != null){
AppPersonnelInfoVo personnelInfoVo = MapstructUtils.convert(appPersonnelInfo, AppPersonnelInfoVo.class);
vo.setPersonnelInfo(personnelInfoVo);
}
return vo;
}
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
Long deviceId = bo.getDeviceId();
Device deviceObj = deviceMapper.selectById(deviceId);
if(deviceObj == null){
throw new RuntimeException("请先将设备入库!!!");
}
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
.eq("device_id", deviceId);
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
// unitName,position,name,id
byte[] unitName = ReliableTextToBitmap.textToBitmapBytes(bo.getUnitName());
byte[] position = ReliableTextToBitmap.textToBitmapBytes(bo.getPosition());
byte[] name = ReliableTextToBitmap.textToBitmapBytes(bo.getName());
byte[] id = ReliableTextToBitmap.textToBitmapBytes(bo.getCode());
Map<String,Object> linkHashMap = new HashMap<>();
linkHashMap.put("unitName",unitName);
linkHashMap.put("position",position);
linkHashMap.put("name",name);
linkHashMap.put("id",id);
String personnelInfo = JSON.toJSONString(linkHashMap);
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY+deviceObj.getDeviceImei(), 1 ,personnelInfo);
log.info("发送点阵数据到设备消息:{}", bo);
if(ObjectUtils.length(appPersonnelInfoVos) == 0){
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
return appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
}else {
UpdateWrapper<AppPersonnelInfo> uw = new UpdateWrapper<>();
uw.eq("device_id", deviceId)
.set("name", bo.getName())
.set("position", bo.getPosition())
.set("unit_name", bo.getUnitName())
.set("code",bo.getCode());
return appPersonnelInfoMapper.update(null, uw)>0;
}
}
}

View File

@ -1,7 +1,10 @@
package com.fuyuanshen.app.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
@ -10,18 +13,18 @@ import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.exception.user.CaptchaExpireException;
import com.fuyuanshen.common.core.utils.MessageUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -30,6 +33,9 @@ import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
@RequiredArgsConstructor
@Slf4j
@ -37,19 +43,71 @@ import java.util.List;
public class AppDeviceShareService {
private final AppDeviceShareMapper appDeviceShareMapper;
private final DeviceMapper deviceMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
public TableDataInfo<AppDeviceShareVo> queryPageList(AppDeviceShareBo bo, PageQuery pageQuery) {
Long userId = AppLoginHelper.getUserId();
bo.setCreateBy(userId);
Page<AppDeviceShareVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
Page<AppDeviceShareVo> result = appDeviceShareMapper.selectAppDeviceShareList(bo, page);
List<AppDeviceShareVo> records = result.getRecords();
records.forEach(AppDeviceShareService::buildDeviceStatus);
return TableDataInfo.build(result);
}
public TableDataInfo<AppDeviceShareVo> queryWebPageList(AppDeviceShareBo bo, PageQuery pageQuery) {
// Long userId = AppLoginHelper.getUserId();
// bo.setCreateBy(userId);
Page<AppDeviceShareVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
Page<AppDeviceShareVo> result = appDeviceShareMapper.selectWebDeviceShareList(bo, page);
List<AppDeviceShareVo> records = result.getRecords();
records.forEach(AppDeviceShareService::buildDeviceStatus);
return TableDataInfo.build(result);
}
private static void buildDeviceStatus(AppDeviceShareVo item) {
// 设备在线状态
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
if("1".equals(onlineStatus)){
item.setOnlineStatus(1);
}else if("2".equals(onlineStatus)){
item.setOnlineStatus(2);
}else{
item.setOnlineStatus(0);
}
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
// 获取电量
if (StringUtils.isNotBlank(deviceStatus)) {
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
item.setBattery(jsonObject.getString("batteryPercentage"));
} else {
item.setBattery("0");
}
String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_LOCATION_KEY_PREFIX);
if (StringUtils.isNotBlank(location)) {
JSONObject jsonObject = JSONObject.parseObject(location);
item.setLatitude(jsonObject.getString("latitude"));
item.setLongitude(jsonObject.getString("longitude"));
}
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
if (StringUtils.isNotBlank(alarmStatus)) {
item.setAlarmStatus(alarmStatus);
}
}
public AppDeviceShareDetailVo getInfo(Long id) {
LambdaQueryWrapper<AppDeviceShare> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(AppDeviceShare::getDeviceId, id);
queryWrapper.eq(AppDeviceShare::getId, id);
List<AppDeviceShareVo> appDeviceShareVos = appDeviceShareMapper.selectVoList(queryWrapper);
if(appDeviceShareVos==null || appDeviceShareVos.isEmpty()){
if (appDeviceShareVos == null || appDeviceShareVos.isEmpty()) {
return null;
}
@ -66,7 +124,7 @@ public class AppDeviceShareService {
shareDetailVo.setDeviceMac(device.getDeviceMac());
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
if(deviceType!=null){
if (deviceType != null) {
shareDetailVo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
}
shareDetailVo.setDevicePic(device.getDevicePic());
@ -78,12 +136,53 @@ public class AppDeviceShareService {
LambdaQueryWrapper<AppPersonnelInfo> qw = new LambdaQueryWrapper<>();
qw.eq(AppPersonnelInfo::getDeviceId, device.getId());
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
if(appPersonnelInfoVos!=null && !appPersonnelInfoVos.isEmpty()){
if (appPersonnelInfoVos != null && !appPersonnelInfoVos.isEmpty()) {
shareDetailVo.setPersonnelInfo(appPersonnelInfoVos.get(0));
}
// 设备在线状态
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
if (StringUtils.isNotBlank(onlineStatus)) {
shareDetailVo.setOnlineStatus(1);
} else {
shareDetailVo.setOnlineStatus(0);
}
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX);
// 获取电量
if (StringUtils.isNotBlank(deviceStatus)) {
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
shareDetailVo.setMainLightMode(jsonObject.getString("mainLightMode"));
shareDetailVo.setLaserLightMode(jsonObject.getString("laserLightMode"));
shareDetailVo.setBatteryPercentage(jsonObject.getString("batteryPercentage"));
shareDetailVo.setChargeState(jsonObject.getString("chargeState"));
shareDetailVo.setBatteryRemainingTime(jsonObject.getString("batteryRemainingTime"));
} else {
shareDetailVo.setBatteryPercentage("0");
}
// 获取经度纬度
String locationKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LOCATION_KEY_PREFIX;
String locationInfo = RedisUtils.getCacheObject(locationKey);
if (StringUtils.isNotBlank(locationInfo)) {
JSONObject jsonObject = JSONObject.parseObject(locationInfo);
shareDetailVo.setLongitude(jsonObject.get("longitude").toString());
shareDetailVo.setLatitude(jsonObject.get("latitude").toString());
shareDetailVo.setAddress((String) jsonObject.get("address"));
}
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
if (StringUtils.isNotBlank(alarmStatus)) {
shareDetailVo.setAlarmStatus(alarmStatus);
}
String lightBrightness = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
if (StringUtils.isNotBlank(lightBrightness)) {
shareDetailVo.setLightBrightness(lightBrightness);
}
return shareDetailVo;
}
/**
* 校验短信验证码
*/
@ -94,14 +193,15 @@ public class AppDeviceShareService {
}
return code.equals(smsCode);
}
public int deviceShare(AppDeviceShareBo bo) {
boolean flag = validateSmsCode(AppLoginHelper.getTenantId(), bo.getPhonenumber(), bo.getSmsCode());
if(!flag){
if (!flag) {
throw new ServiceException("验证码错误");
}
Device device = deviceMapper.selectById(bo.getDeviceId());
if(device==null){
if (device == null) {
throw new ServiceException("设备不存在");
}
Long userId = AppLoginHelper.getUserId();
@ -109,27 +209,56 @@ public class AppDeviceShareService {
lqw.eq(AppDeviceShare::getDeviceId, bo.getDeviceId());
lqw.eq(AppDeviceShare::getPhonenumber, bo.getPhonenumber());
Long count = appDeviceShareMapper.selectCount(lqw);
if(count>0){
if (count > 0) {
UpdateWrapper<AppDeviceShare> uw = new UpdateWrapper<>();
uw.eq("device_id", bo.getDeviceId());
uw.eq("phonenumber", bo.getPhonenumber());
uw.set("permission", bo.getPermission());
uw.set("update_by", userId);
uw.set("create_by", userId);
uw.set("update_time", new Date());
return appDeviceShareMapper.update(uw);
}else {
} else {
AppDeviceShare appDeviceShare = new AppDeviceShare();
appDeviceShare.setDeviceId(bo.getDeviceId());
appDeviceShare.setPhonenumber(bo.getPhonenumber());
appDeviceShare.setPermission(bo.getPermission());
appDeviceShare.setCreateBy(userId);
return appDeviceShareMapper.insert(appDeviceShare);
}
}
}
public int remove(Long[] ids) {
return appDeviceShareMapper.deleteByIds(Arrays.asList(ids));
}
public TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery) {
String username = AppLoginHelper.getUsername();
bo.setPhonenumber(username);
Page<AppDeviceShareVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
IPage<AppDeviceShareVo> result = appDeviceShareMapper.otherDeviceShareList(bo, page);
List<AppDeviceShareVo> records = result.getRecords();
records.forEach(AppDeviceShareService::buildDeviceStatus);
return TableDataInfo.build(result);
}
/**
* 查询设备分享列表(web)
*
* @param bo
* @param pageQuery
* @return
*/
public TableDataInfo<AppDeviceShareVo> queryWebList(AppDeviceShareBo bo, PageQuery pageQuery) {
Page<AppDeviceShareVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
Page<AppDeviceShareVo> result = appDeviceShareMapper.selectWebDeviceShareList(bo, page);
List<AppDeviceShareVo> records = result.getRecords();
records.forEach(AppDeviceShareService::buildDeviceStatus);
return TableDataInfo.build(result);
}
}

View File

@ -8,6 +8,7 @@ import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.oss.core.OssClient;
import com.fuyuanshen.common.oss.factory.OssFactory;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.utils.FileHashUtil;
import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
@ -15,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
/**
@ -31,24 +33,38 @@ public class AppFileService {
private final IAppBusinessFileService appBusinessFileService;
private final FileHashUtil fileHashUtil;
private final ISysOssService ossService;
public List<AppFileVo> list(AppBusinessFileBo bo) {
bo.setCreateBy(AppLoginHelper.getUserId());
// bo.setCreateBy(AppLoginHelper.getUserId());
return appBusinessFileService.queryAppFileList(bo);
}
public Boolean add(AppFileDto bo) {
/**
* APP文件上传
*/
public Boolean add(AppFileDto bo) throws IOException {
MultipartFile[] files = bo.getFiles();
if(files == null || files.length == 0){
if (files == null || files.length == 0) {
throw new ServiceException("请选择要上传的文件");
}
if(files.length > 5){
if (files.length > 5) {
throw new ServiceException("最多只能上传5个文件");
}
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
// 上传文件
SysOssVo upload = sysOssService.upload(file);
// SysOssVo upload = sysOssService.upload(file);
String fileHash = fileHashUtil.hash(file);
SysOssVo upload = ossService.updateHash(file, fileHash);
// 强制将HTTP替换为HTTPS
if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
}
if (upload == null) {
return false;
@ -66,9 +82,10 @@ public class AppFileService {
return true;
}
public Boolean delete(Long[] ids) {
AppBusinessFileBo bo = new AppBusinessFileBo();
bo.setCreateBy(AppLoginHelper.getUserId());
// bo.setCreateBy(AppLoginHelper.getUserId());
bo.setIds(List.of(ids));
List<AppBusinessFileVo> appBusinessFileVos = appBusinessFileService.queryList(bo);
List<Long> fileIds = appBusinessFileVos.stream().map(AppBusinessFileVo::getFileId).toList();

View File

@ -4,6 +4,11 @@ import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.domain.vo.AppRoleVo;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.common.core.constant.Constants;
@ -23,6 +28,8 @@ import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.exception.TenantException;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.system.domain.vo.SysTenantVo;
import com.fuyuanshen.system.service.ISysTenantService;
import lombok.RequiredArgsConstructor;
@ -33,6 +40,7 @@ import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* 登录校验方法
@ -51,7 +59,10 @@ public class AppLoginService {
private Integer lockTime;
private final ISysTenantService tenantService;
private final IAppRoleService roleService;
private final IAppUserService appUserService;
private final IAppDeviceShareService appDeviceShareService;
private final IAppDeviceBindRecordService appDeviceBindRecordService;
private final DeviceService deviceService;
/**
@ -185,4 +196,60 @@ public class AppLoginService {
}
}
public void cancelAccount() {
try {
AppLoginUser loginUser = AppLoginHelper.getLoginUser();
// AppLoginUser loginUser = new AppLoginUser();
// loginUser.setUserId(1988398584423133187L);
// loginUser.setUsername("19022528079");
if (ObjectUtil.isNull(loginUser)) {
return;
}
appUserService.deleteWithValidByIds(Collections.singletonList(loginUser.getUserId()),true);
AppDeviceBindRecordBo appDeviceBindRecordBo = new AppDeviceBindRecordBo();
appDeviceBindRecordBo.setBindingUserId(loginUser.getUserId());
List<AppDeviceBindRecordVo> appDeviceBindRecordVos = appDeviceBindRecordService.queryList(appDeviceBindRecordBo);
if(ObjectUtil.length(appDeviceBindRecordVos)>0){
Set<Long> deviceIds = appDeviceBindRecordVos.stream().map(AppDeviceBindRecordVo::getDeviceId).collect(Collectors.toSet());
appDeviceShareService.deleteByDeviceIds(deviceIds);
List<Long> ids = appDeviceBindRecordVos.stream()
.map(AppDeviceBindRecordVo::getId)
.collect(Collectors.toList());
appDeviceBindRecordService.deleteWithValidByIds(ids, true);
log.info("删除绑定关系表数据ids={}",ids);
// 检查设备id是否存在绑定关系
for (Long deviceId : deviceIds){
// 根据设备id查询是否存在绑定关系
Long count = appDeviceBindRecordService.checkDeviceExistBindRecord(deviceId);
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id",deviceId);
if(count>0){
updateWrapper.set("binding_status",1);
}else{
updateWrapper.set("binding_status",0);
}
deviceService.update(updateWrapper);
}
}
if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
// 超级管理员 登出清除动态租户
TenantHelper.clearDynamic();
}
recordLogininfor(loginUser.getTenantId(), loginUser.getUsername(), Constants.LOGOUT, "用户注销成功");
} catch (NotLoginException ignored) {
} finally {
try {
StpUtil.logout();
} catch (NotLoginException ignored) {
}
}
}
}

View File

@ -0,0 +1,156 @@
package com.fuyuanshen.app.service;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppUser;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.app.model.AppRegisterBody;
import com.fuyuanshen.app.model.AppUpdatePasswordBody;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.enums.UserType;
import com.fuyuanshen.common.core.exception.user.CaptchaException;
import com.fuyuanshen.common.core.exception.user.CaptchaExpireException;
import com.fuyuanshen.common.core.exception.user.UserException;
import com.fuyuanshen.common.core.utils.MessageUtils;
import com.fuyuanshen.common.core.utils.ServletUtils;
import com.fuyuanshen.common.core.utils.SpringUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.log.event.LogininforEvent;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.common.web.config.properties.CaptchaProperties;
import com.fuyuanshen.system.domain.SysUser;
import com.fuyuanshen.system.domain.bo.SysUserBo;
import com.fuyuanshen.system.mapper.SysUserMapper;
import com.fuyuanshen.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* 注册校验方法
*
* @author Lion Li
*/
@RequiredArgsConstructor
@Service
public class AppRegisterService {
private final IAppUserService userService;
private final AppUserMapper userMapper;
/**
* 注册
*/
public void register(AppRegisterBody registerBody) {
String tenantId = registerBody.getTenantId();
String username = registerBody.getPhonenumber();
String password = registerBody.getPassword();
boolean codeValidate = validateRegisterSmsCode(tenantId, username, registerBody.getSmsCode());
if (!codeValidate) {
throw new CaptchaException();
}
// 校验用户类型是否存在
String userType = UserType.APP_USER.getUserType();
boolean exist = TenantHelper.dynamic(tenantId, () -> {
return userMapper.exists(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getUserName, username));
});
if (exist) {
throw new UserException("user.register.save.error", username);
}
AppUser appUser = new AppUser();
appUser.setPhonenumber(username);
appUser.setUserName(username);
appUser.setStatus("0");
appUser.setLoginDate(new Date());
appUser.setLoginIp(ServletUtils.getClientIP());
appUser.setTenantId(tenantId);
appUser.setPassword(password);
appUser.setUserType(userType);
userMapper.insert(appUser);
recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
}
/**
* 注册校验短信验证码
*/
private boolean validateRegisterSmsCode(String tenantId, String phonenumber, String smsCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.REGISTER_CODE_KEY + phonenumber);
if (StringUtils.isBlank(code)) {
recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
return code.equals(smsCode);
}
/**
* 忘记密码校验验证码
*/
private boolean validateForgetPasswordCode(String tenantId, String phonenumber, String smsCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.FORGET_PASSWORD_CODE_KEY + phonenumber);
if (StringUtils.isBlank(code)) {
recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
return code.equals(smsCode);
}
/**
* 记录登录信息
*
* @param tenantId 租户ID
* @param username 用户名
* @param status 状态
* @param message 消息内容
* @return
*/
private void recordLogininfor(String tenantId, String username, String status, String message) {
LogininforEvent logininforEvent = new LogininforEvent();
logininforEvent.setTenantId(tenantId);
logininforEvent.setUsername(username);
logininforEvent.setStatus(status);
logininforEvent.setMessage(message);
logininforEvent.setRequest(ServletUtils.getRequest());
SpringUtils.context().publishEvent(logininforEvent);
}
public void forgetPassword(AppRegisterBody registerBody) {
String tenantId = registerBody.getTenantId();
String username = registerBody.getPhonenumber();
String password = registerBody.getPassword();
boolean codeValidate = validateForgetPasswordCode(tenantId, username, registerBody.getSmsCode());
if (!codeValidate) {
throw new CaptchaException();
}
boolean exist = TenantHelper.dynamic(tenantId, () -> {
return userMapper.exists(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getUserName, username));
});
if (!exist) {
throw new UserException("用户不存在");
}
UpdateWrapper<AppUser> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_name", username)
.set("password", password);
userMapper.update(updateWrapper);
}
public void updatePassword(AppUpdatePasswordBody body) {
String username = AppLoginHelper.getUsername();
String password = body.getPassword();
UpdateWrapper<AppUser> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("user_name", username)
.set("password", password);
userMapper.update(updateWrapper);
}
}

View File

@ -0,0 +1,540 @@
package com.fuyuanshen.app.service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppBusinessFile;
import com.fuyuanshen.app.domain.bo.AppBusinessFileBo;
import com.fuyuanshen.app.domain.dto.AppAudioFileDto;
import com.fuyuanshen.app.domain.dto.AppFileRenameDto;
import com.fuyuanshen.app.domain.vo.AppFileVo;
import com.fuyuanshen.app.http.HttpTtsClient;
import com.fuyuanshen.app.mapper.AppBusinessFileMapper;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.utils.AlibabaTTSUtil;
import com.fuyuanshen.equipment.utils.AudioProcessUtil;
import com.fuyuanshen.equipment.utils.FileHashUtil;
import com.fuyuanshen.equipment.utils.Mp3Duration;
import com.fuyuanshen.system.domain.vo.SysOssVo;
import com.fuyuanshen.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* 音频处理服务
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class AudioProcessService {
// 配置参数
private static final int MAX_AUDIO_SIZE = 5 * 1024 * 1024; // 5MB
private static final List<String> SUPPORTED_FORMATS = Arrays.asList(
".wav", ".mp3", ".aac", ".flac", ".m4a", ".ogg"
);
private final AudioProcessUtil audioProcessUtil;
private final AlibabaTTSUtil alibabaTTSUtil;
private final FileHashUtil fileHashUtil;
private final ISysOssService ossService;
private final IAppBusinessFileService appBusinessFileService;
private final AppBusinessFileMapper appBusinessFileMapper;
/**
* 处理上传的音频文件
*/
public List<String> processAudio(MultipartFile file) {
// 1. 参数校验
validateAudioFile(file);
File tempFile = null;
try {
// 2. 创建临时文件
tempFile = createTempAudioFile(file);
// 3. 转码为标准PCM-WAV格式
byte[] pcmData = audioProcessUtil.convertToStandardWav(tempFile);
log.info("音频处理成功,输出数据大小: {} bytes", pcmData.length);
// 获取音频信息
// String audioInfo = audioProcessUtil.getAudioInfo(pcmData);
// log.info("音频处理成功,音频信息: {}", audioInfo);
//
// // 保存测试文件(用于验证)
// String savedPath = audioProcessUtil.saveWavToFile(pcmData, "test_output.wav");
// if (savedPath != null) {
// log.info("测试文件已保存: {}", savedPath);
// }
// 将byte[]转换为16进制字符串列表
List<String> hexList = audioProcessUtil.bytesToHexList(pcmData);
log.info("音频处理完成,原始数据大小: {} bytes, 16进制数据长度: {}",
pcmData.length, hexList.size());
return hexList;
} catch (Exception e) {
log.error("音频处理失败", e);
throw new RuntimeException("音频处理失败", e);
} finally {
// 4. 清理临时文件
deleteTempFile(tempFile);
}
}
/**
* 生成标准PCM数据单声道16K采样率16bit深度包含44字节WAV头
* 数据总大小不超过2MB如果超过将抛出异常
* @param text 要转换的文本内容
* @return 标准PCM数据字节数组WAV格式
* @throws IOException 处理失败时抛出
* @throws IllegalArgumentException 如果生成的数据超过2MB
*/
public List<String> generateStandardPcmData(String text) throws IOException {
// 参数校验
if (text == null || text.trim().isEmpty()) {
throw new IllegalArgumentException("文本内容不能为空");
}
if (text.length() > 100) {
throw new IllegalArgumentException("文本长度超过限制最大100字符");
}
log.info("输入文本长度: {}", text.length());
try {
byte[] rawPcmData = alibabaTTSUtil.generateStandardPcmData(text);
// 使用AudioProcessUtil转换成带头44字节 PCM
byte[] pcmData = audioProcessUtil.rawPcmToStandardWav(rawPcmData);
// String savedPath = audioProcessUtil.saveWavToFile(pcmData, "test_output.wav");
// if (savedPath != null) {
// log.info("测试文件已保存: {}", savedPath);
// }
// 保存WAV文件到本地
String savedPath = saveByteArrayToFile(pcmData, "tts_output.wav");
if (savedPath != null) {
log.info("WAV文件已保存: {}", savedPath);
}
// 将byte[]转换为16进制字符串列表
List<String> hexList = audioProcessUtil.bytesToHexList(pcmData);
log.info("generateStandardPcmData音频处理完成原始数据大小: {} bytes, 16进制数据长度: {}",
pcmData.length, hexList.size());
return hexList;
} finally {
// 4. 清理临时文件
}
}
public String saveWavFileLocally(String text, String filename) throws IOException {
// 参数校验
if (text == null || text.trim().isEmpty()) {
throw new IllegalArgumentException("文本内容不能为空");
}
if (filename == null || filename.trim().isEmpty()) {
filename = "tts_output.wav"; // 默认文件名
}
try {
// 生成PCM数据
byte[] rawPcmData = alibabaTTSUtil.generateStandardPcmData(text);
// 转换为标准WAV格式添加44字节头部
byte[] wavData = audioProcessUtil.rawPcmToStandardWav(rawPcmData);
// 保存到本地文件
String filePath = saveByteArrayToFile(wavData, filename);
log.info("WAV文件已保存: {}", filePath);
return filePath;
} catch (Exception e) {
log.error("保存WAV文件失败: {}", e.getMessage(), e);
throw new IOException("保存WAV文件失败", e);
}
}
private String saveByteArrayToFile(byte[] data, String filename) throws IOException {
// 确定保存路径(可以是临时目录或指定目录)
String directory = System.getProperty("java.io.tmpdir"); // 使用系统临时目录
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
// 创建完整文件路径
File file = new File(dir, filename);
// 写入文件
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
}
return file.getAbsolutePath();
}
private String saveByteArrayToFile(InputStream inputStream, String filename) throws IOException {
// 确定保存路径(可以是临时目录或指定目录)
String directory = System.getProperty("java.io.tmpdir"); // 使用系统临时目录
File dir = new File(directory);
if (!dir.exists()) {
dir.mkdirs();
}
// 创建完整文件路径
File file = new File(dir, filename);
// 从输入流读取数据并写入文件
try (FileOutputStream fos = new FileOutputStream(file);
InputStream is = inputStream) {
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
return file.getAbsolutePath();
}
/**
* 验证音频文件
*/
private void validateAudioFile(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("上传文件不能为空");
}
if (!isAudioFile(file.getOriginalFilename())) {
throw new IllegalArgumentException("只允许上传音频文件");
}
if (file.getSize() > MAX_AUDIO_SIZE) {
throw new IllegalArgumentException("音频大小不能超过5MB");
}
}
/**
* 判断是否是支持的音频格式
*/
private boolean isAudioFile(String filename) {
if (filename == null || filename.lastIndexOf('.') == -1) {
return false;
}
String ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();
return SUPPORTED_FORMATS.contains(ext);
}
/**
* 创建临时音频文件
*/
private File createTempAudioFile(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String extension = "";
if (originalFilename != null && originalFilename.contains(".")) {
extension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
File tempFile = File.createTempFile("audio-", extension);
file.transferTo(tempFile);
log.debug("创建临时音频文件: {}", tempFile.getAbsolutePath());
return tempFile;
}
/**
* 删除临时文件
*/
private void deleteTempFile(File file) {
if (file != null && file.exists()) {
if (file.delete()) {
log.debug("删除临时文件成功: {}", file.getAbsolutePath());
} else {
log.warn("无法删除临时文件: {}", file.getAbsolutePath());
}
}
}
/**
* 提取文本
*/
public String extract(MultipartFile file) throws Exception {
String name = file.getOriginalFilename();
if (name == null ||
(!name.endsWith(".txt") && !name.endsWith(".docx"))) {
throw new IllegalArgumentException("仅支持 .txt 或 .docx");
}
if (file.getSize() > MAX_AUDIO_SIZE) {
throw new IllegalArgumentException("文件超过5MB");
}
String text;
/* 全程流式,不落地磁盘,不一次性读字节数组 */
try (InputStream in = file.getInputStream()) {
if (name.endsWith(".txt")) {
text = readTxt(in);
} else {
text = readDocx(in);
}
}
return text;
}
/* ---------- txt按行读StringBuilder 复用 ---------- */
private String readTxt(InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder(4096);
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
return sb.toString();
}
/* ---------- docxZipInputStream 只扫 document.xml ---------- */
private String readDocx(InputStream in) throws IOException {
ZipInputStream zin = new ZipInputStream(in);
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
if ("word/document.xml".equals(e.getName())) {
return staxExtract(zin); // 流式读 XML
}
}
return "";
}
/* ---------- StAX 流式提取 <w:t> ---------- */
private String staxExtract(InputStream xml) throws IOException {
XMLStreamReader r = null;
StringBuilder sb = new StringBuilder(4096);
try {
//System.out.println(new String(xml.readAllBytes()));
r = XMLInputFactory.newInstance().createXMLStreamReader(xml);
while (r.hasNext()) {
if (r.next() == XMLStreamConstants.START_ELEMENT &&
"t".equals(r.getLocalName())) {
String elementText = r.getElementText();
sb.append(elementText);
}
}
} catch (XMLStreamException ex) {
throw new IOException(ex);
} finally {
if (r != null) try { r.close(); } catch (XMLStreamException ignore) {}
}
return sb.toString();
}
public String uploadAudioToOss(AppAudioFileDto bo) {
MultipartFile file = bo.getFile();
// 校验文件格式和大小
validateAudioFileForRestful(file);
// 上传文件
// SysOssVo upload = sysOssService.upload(file);
String filename = file.getOriginalFilename();
String savedPath = null;
try {
String fileHash = fileHashUtil.hash(file);
SysOssVo upload = ossService.updateHash(file, fileHash);
// 强制将HTTP替换为HTTPS
if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
}
String fileSuffix = filename.substring(filename.lastIndexOf('.')).toLowerCase();
AppBusinessFileBo appBusinessFileBo = new AppBusinessFileBo();
appBusinessFileBo.setFileId(upload.getOssId());
appBusinessFileBo.setBusinessId(bo.getDeviceId());
appBusinessFileBo.setFileType(3L);
appBusinessFileBo.setCreateBy(AppLoginHelper.getUserId());
savedPath = saveByteArrayToFile(file.getInputStream(), generateRandomFileName(fileSuffix));
if (savedPath != null) {
log.info("MP3文件已保存: {}", savedPath);
Integer mp3Duration = Mp3Duration.getMp3Duration(savedPath);
log.info("MP3文件时长: {} 秒", mp3Duration);
appBusinessFileBo.setDuration(mp3Duration);
}
appBusinessFileService.insertByBo(appBusinessFileBo);
if (upload != null) {
return upload.getUrl();
}
} catch (Exception e){
log.error("上传音频文件失败", e);
}finally {
log.info("删除临时文件: {}", savedPath);
if(savedPath != null){
deleteTempFile(new File(savedPath));
}
}
return null;
}
/**
* 校验音频文件格式
*/
private void validateAudioFileForRestful(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("上传文件不能为空");
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null) {
throw new IllegalArgumentException("文件名不能为空");
}
List<String> SUPPORTED_FORMATS = Arrays.asList(
".wav", ".mp3", ".pcm"
);
String ext = originalFilename.substring(originalFilename.lastIndexOf('.')).toLowerCase();
// 检查文件扩展名
if (!SUPPORTED_FORMATS.contains(ext)) {
throw new IllegalArgumentException("只允许上传MP3、WAV、PCM格式的音频文件");
}
// 检查文件大小
if (file.getSize() > MAX_AUDIO_SIZE) {
throw new IllegalArgumentException("音频大小不能超过5MB");
}
}
/**
* 判断文件是否为支持的音频格式
*/
private boolean isSupportedFormat(String filename) {
if (filename == null || filename.lastIndexOf('.') == -1) {
return false;
}
String ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();
return SUPPORTED_FORMATS.contains(ext);
}
public String textToSpeech(Long deviceId,String text, String fileSuffix) {
//支持PCM/WAV/MP3格式
if (fileSuffix == null || fileSuffix.isEmpty()) {
fileSuffix = "mp3";
}
fileSuffix = fileSuffix.toLowerCase();
List<String> SUPPORTED_FORMATS = Arrays.asList(
"wav", "mp3", "pcm"
);
boolean contains = SUPPORTED_FORMATS.contains(fileSuffix);
if (!contains) {
throw new IllegalArgumentException("不支持的音频格式");
}
String accessKeyId = "LTAI5t66moCkhNC32TDJ5ReP";
String accessKeySecret = "2F3sdoBJ08bYvJcuDgSkLnJwGXsvYH";
String appKey = "lbGuq5K5bEH4uxmT";
String savedPath = null;
try {
// 使用HTTP方式调用
HttpTtsClient httpClient = new HttpTtsClient(accessKeyId, accessKeySecret, appKey);
//
byte[] mp3Data = httpClient.synthesizeTextToMp3(text);
// byte[] mp3Data = alibabaTTSUtil.synthesizeTextToMp3(text);
SysOssVo upload = ossService.upload(mp3Data, generateRandomFileName(fileSuffix));
// 强制将HTTP替换为HTTPS
if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
}
AppBusinessFileBo appBusinessFileBo = new AppBusinessFileBo();
appBusinessFileBo.setFileId(upload.getOssId());
appBusinessFileBo.setBusinessId(deviceId);
appBusinessFileBo.setFileType(3L);
appBusinessFileBo.setCreateBy(AppLoginHelper.getUserId());
savedPath = saveByteArrayToFile(mp3Data, generateRandomFileName(fileSuffix));
if (savedPath != null) {
log.info("MP3文件已保存: {}", savedPath);
Integer mp3Duration = Mp3Duration.getMp3Duration(savedPath);
log.info("MP3文件时长: {} 秒", mp3Duration);
appBusinessFileBo.setDuration(mp3Duration);
}
appBusinessFileService.insertByBo(appBusinessFileBo);
if (upload != null) {
return upload.getUrl();
}
} catch (Exception e){
log.error("上传音频文件失败", e);
} finally {
log.info("删除临时文件: {}", savedPath);
if(savedPath != null){
deleteTempFile(new File(savedPath));
}
}
return null;
}
private static final Random random = new Random();
private static final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
/**
* 生成纯随机文件名(无原文件名依赖)
*/
public static String generateRandomFileName(String extension) {
String timestamp = LocalDateTime.now().format(formatter);
int randomNum = random.nextInt(10000);
String uuidPart = UUID.randomUUID().toString().substring(0, 8);
if (!extension.startsWith(".")) {
extension = "." + extension;
}
return timestamp + "_" + String.format("%04d", randomNum) + "_" + uuidPart + extension;
}
public List<AppFileVo> queryAudioFileList(Long deviceId) {
if(deviceId == null){
return null;
}
AppBusinessFileBo bo = new AppBusinessFileBo();
bo.setBusinessId(deviceId);
bo.setFileType(3L);
List<AppFileVo> appFileVos = appBusinessFileService.queryAppFileList(bo);
return appFileVos;
}
public R<Void> deleteAudioFile(Long fileId,Long deviceId) {
UpdateWrapper<AppBusinessFile> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("file_id",fileId);
updateWrapper.eq("business_id",deviceId);
appBusinessFileMapper.delete(updateWrapper);
return R.ok();
}
public R<Void> renameAudioFile(AppFileRenameDto bo) {
UpdateWrapper<AppBusinessFile> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("file_id",bo.getFileId());
updateWrapper.eq("business_id",bo.getDeviceId());
updateWrapper.set("re_name",bo.getFileName());
appBusinessFileMapper.update(updateWrapper);
return R.ok();
}
}

View File

@ -0,0 +1,85 @@
package com.fuyuanshen.app.service;
import com.fuyuanshen.web.util.VideoProcessUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Arrays;
import java.util.List;
/**
* 视频处理服务
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class VideoProcessService {
// 配置参数
private static final int MAX_VIDEO_SIZE = 10 * 1024 * 1024;
private static final List<String> SUPPORTED_FORMATS = Arrays.asList(".mp4", ".avi", ".mov", ".mkv");
private static final int FRAME_RATE = 15;
private static final int DURATION = 2;
private static final int WIDTH = 160;
private static final int HEIGHT = 80;
private final VideoProcessUtil videoProcessUtil;
public List<String> processVideo(MultipartFile file, int code) {
// 1. 参数校验
validateVideoFile(file);
File tempFile = null;
try {
// 2. 创建临时文件
tempFile = videoProcessUtil.createTempVideoFile(file);
// 3. 处理视频并提取帧数据
List<String> hexList = videoProcessUtil.processVideoToHex(
tempFile, FRAME_RATE, DURATION, WIDTH, HEIGHT, code
);
log.info("code: {} hexList(前100个): {}", code,
hexList.subList(0, Math.min(100, hexList.size())));
log.info("视频处理成功生成Hex数据长度: {}", hexList.size());
return hexList;
} catch (Exception e) {
log.error("视频处理失败", e);
throw new RuntimeException("视频处理失败", e);
} finally {
// 4. 清理临时文件
videoProcessUtil.deleteTempFile(tempFile);
}
}
/**
* 验证视频文件
*/
private void validateVideoFile(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("上传文件不能为空");
}
if (!isVideoFile(file.getOriginalFilename())) {
throw new IllegalArgumentException("只允许上传视频文件");
}
if (file.getSize() > MAX_VIDEO_SIZE) {
throw new IllegalArgumentException("视频大小不能超过10MB");
}
}
/**
* 判断是否是支持的视频格式
*/
private boolean isVideoFile(String filename) {
if (filename == null || filename.lastIndexOf('.') == -1) {
return false;
}
String ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();
return SUPPORTED_FORMATS.contains(ext);
}
}

View File

@ -0,0 +1,48 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
import java.util.List;
/**
* MQTT消息基础模型
*/
@Data
public class MqttMessage {
/**
* 请求ID用于匹配请求和响应
*/
private String requestId;
/**
* 设备IMEI
*/
private String imei;
/**
* 时间戳(毫秒)
*/
private Long timestamp;
/**
* 功能类型
*/
private Integer funcType;
/**
* 数据内容
*/
private Object data;
/**
* 状态(响应时使用)
*/
private String status;
/**
* 批量数据(设备上报时使用)
*/
private List<SensorData> batch;
}

View File

@ -0,0 +1,26 @@
package com.fuyuanshen.global.mqtt.base;
/**
* MQTT消息处理接口
*/
public interface MqttMessageRule {
/**
* 获取命令类型
* @return 命令类型
*/
String getCommandType();
/**
* 执行处理
* @param context 处理上下文
*/
void execute(MqttRuleContext context);
/**
* 获取优先级,数值越小优先级越高
* @return 优先级
*/
default int getPriority() {
return 0;
}
}

View File

@ -0,0 +1,32 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
import java.util.Map;
/**
* MQTT消息处理上下文
*/
@Data
public class MqttRuleContext {
/**
* 命令类型
*/
private byte commandType;
/**
* 转换后的参数数组
*/
private Object[] convertArr;
/**
* 设备IMEI
*/
private String deviceImei;
/**
* 数据来源Redis
*/
private String dataFromRedis;
/**
* MQTT消息负载字典
*/
private Map<String, Object> payloadDict;
}

View File

@ -0,0 +1,48 @@
package com.fuyuanshen.global.mqtt.base;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* MQTT消息引擎
*/
@Component
public class MqttRuleEngine {
// @Autowired
// @Qualifier("threadPoolTaskExecutor")
// private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private final LinkedHashMap<String, MqttMessageRule> rulesMap = new LinkedHashMap<>();
public MqttRuleEngine(List<MqttMessageRule> rules) {
// 按优先级排序
rules.sort(Comparator.comparing(MqttMessageRule::getPriority));
rules.forEach(rule -> rulesMap.put(rule.getCommandType(), rule)
);
}
/**
* 执行匹配
*
* @param context 处理上下文
* @return
*/
public boolean executeRule(MqttRuleContext context) {
int commandType = context.getCommandType();
MqttMessageRule mqttMessageRule = rulesMap.get("Light_" + commandType);
if (mqttMessageRule != null) {
// threadPoolTaskExecutor.execute(() -> mqttMessageRule.execute(context));
mqttMessageRule.execute(context);
return true;
}
return false;
}
}

View File

@ -0,0 +1,29 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
/**
* MQTT主题信息模型
*/
@Data
public class MqttTopicInfo {
/**
* 操作类型 (command/status/report)
*/
private String operation;
/**
* 租户编码
*/
private String tenantCode;
/**
* 设备类型
*/
private String deviceType;
/**
* 设备IMEI
*/
private String imei;
}

View File

@ -0,0 +1,65 @@
package com.fuyuanshen.global.mqtt.base;
import cn.hutool.core.lang.Dict;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Collections;
import org.springframework.stereotype.Component;
@Component
public final class MqttXinghanCommandType {
private MqttXinghanCommandType() {}
public enum XinghanCommandTypeEnum {
/**
* 星汉设备主动上报数据
*/
GRADE_INFO(101),
/**
* 星汉开机LOGO
*/
PIC_TRANS(102),
/**
* 星汉设备发送消息 (XingHan send msg)
*/
TEX_TRANS(103),
BREAK_NEWS(104),
UNKNOWN(0);
private final int value;
XinghanCommandTypeEnum(int value) { this.value = value; }
public int getValue() { return value; }
}
private static final Map<String, XinghanCommandTypeEnum> KEY_TO_TYPE;
static {
LinkedHashMap<String, XinghanCommandTypeEnum> map = new LinkedHashMap<>();
map.put("sta_DetectGrade", XinghanCommandTypeEnum.GRADE_INFO);
map.put("sta_PowerTime", XinghanCommandTypeEnum.GRADE_INFO);
map.put("sta_longitude", XinghanCommandTypeEnum.GRADE_INFO);
map.put("sta_latitude", XinghanCommandTypeEnum.GRADE_INFO);
map.put("sta_PicTrans", XinghanCommandTypeEnum.PIC_TRANS);
map.put("sta_TexTrans", XinghanCommandTypeEnum.TEX_TRANS);
map.put("sta_BreakNews", XinghanCommandTypeEnum.BREAK_NEWS);
KEY_TO_TYPE = Collections.unmodifiableMap(map);
}
public static int computeVirtualCommandType(Dict payloadDict) {
if (payloadDict == null) {
return XinghanCommandTypeEnum.UNKNOWN.getValue();
}
try {
for (String key : KEY_TO_TYPE.keySet()) {
if (payloadDict.containsKey(key)) {
return KEY_TO_TYPE.get(key).getValue();
}
}
} catch (Exception ex) {
return XinghanCommandTypeEnum.UNKNOWN.getValue();
}
return XinghanCommandTypeEnum.UNKNOWN.getValue();
}
}

View File

@ -0,0 +1,74 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonProperty;
@Data
public class MqttXinghanJson {
/**
* 第一键值对静电预警档位3,2,1,0,分别表示高档/中档/低挡/关闭.
*/
@JsonProperty("sta_DetectGrade")
private Integer staDetectGrade;
/**
* 第二键值对照明档位2,1,0,分别表示弱光/强光/关闭
*/
@JsonProperty("sta_LightGrade")
private Integer staLightGrade;
/**
* 第三键值对SOS档位2,1,0, 分别表示红蓝模式/爆闪模式/关闭
*/
@JsonProperty("sta_SOSGrade")
public Integer staSOSGrade;
/**
* 第四键值对剩余照明时间0-5999单位分钟。
*/
@JsonProperty("sta_PowerTime")
public Integer staPowerTime;
/**
* 第五键值对剩余电量百分比0-100
*/
@JsonProperty("sta_PowerPercent")
public Integer staPowerPercent;
/**
* 第六键值对, 近电预警级别, 0-无预警1-弱预警2-中预警3-强预警4-非常强预警。
*/
@JsonProperty("sta_DetectResult")
public Integer staDetectResult;
/**
* 第七键值对, 静止报警状态0-未静止报警1-正在静止报警。
*/
@JsonProperty("sta_ShakeBit")
public Integer staShakeBit;
/**
* 第八键值对, 4G信号强度0-32数值越大信号越强。
*/
@JsonProperty("sta_4gSinal")
public Integer sta4gSinal;
/**
* 第九键值对IMIE卡号
*/
@JsonProperty("sta_imei")
public String staimei;
/**
* 第十键值对,经度
*/
@JsonProperty("sta_longitude")
public String stalongitude;
/**
* 第十一键值对,纬度
*/
@JsonProperty("sta_latitude")
public String stalatitude;
/**
* 第十二键值对系统现状0关机1仅充电2开机未充电,3开机且充电
*/
@JsonProperty("sta_system")
public String stasystem;
/**
* 电量百分比(适配控制列表显示)
*/
public String batteryPercentage;
}

View File

@ -0,0 +1,26 @@
package com.fuyuanshen.global.mqtt.base;
/**
* MQTT消息处理接口
*/
public interface NewMqttMessageRule {
/**
* 获取命令类型
* @return 命令类型
*/
String getCommandType();
/**
* 执行处理
* @param context 处理上下文
*/
void execute(NewMqttRuleContext context);
/**
* 获取优先级,数值越小优先级越高
* @return 优先级
*/
default int getPriority() {
return 0;
}
}

View File

@ -0,0 +1,25 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
import java.util.Map;
/**
* MQTT消息处理上下文
*/
@Data
public class NewMqttRuleContext {
/**
* 命令类型
*/
private String commandType;
/**
* 设备IMEI
*/
private String deviceImei;
/**
* MQTT消息负载字典
*/
private Map<String, Object> payloadDict;
}

View File

@ -0,0 +1,44 @@
package com.fuyuanshen.global.mqtt.base;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* MQTT消息引擎
*/
@Component
public class NewMqttRuleEngine {
// @Autowired
// @Qualifier("threadPoolTaskExecutor")
// private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private final LinkedHashMap<String, NewMqttMessageRule> rulesMap = new LinkedHashMap<>();
public NewMqttRuleEngine(List<NewMqttMessageRule> rules) {
// 按优先级排序
rules.sort(Comparator.comparing(NewMqttMessageRule::getPriority));
rules.forEach(rule -> rulesMap.put(rule.getCommandType(), rule)
);
}
/**
* 执行匹配
* @param context 处理上下文
* @return
*/
public boolean executeRule(NewMqttRuleContext context) {
String commandType = context.getCommandType();
// String funcType = context.getFuncType();
NewMqttMessageRule mqttMessageRule = rulesMap.get(commandType);
if (mqttMessageRule != null) {
// threadPoolTaskExecutor.execute(() -> mqttMessageRule.execute(context));
mqttMessageRule.execute(context);
return true;
}
return false;
}
}

View File

@ -0,0 +1,24 @@
package com.fuyuanshen.global.mqtt.base;
import lombok.Data;
/**
* 传感器数据模型
*/
@Data
public class SensorData {
/**
* 传感器名称
*/
private String sensor;
/**
* 传感器值
*/
private Object value;
/**
* 时间戳(毫秒)
*/
private Long timestamp;
}

View File

@ -1,4 +1,4 @@
package com.fuyuanshen.system.mqtt.config;
package com.fuyuanshen.global.mqtt.config;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
@ -7,30 +7,46 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
/**
* @Author: HarryLin
* @Date: 2025/3/20 14:40
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Configuration
public class MqttConfiguration {
@Autowired
private MqttPropertiesConfig mqttPropertiesConfig;
/** 创建连接工厂 **/
/**
* 创建连接工厂
**/
@Bean
public MqttPahoClientFactory mqttPahoClientFactory(){
public MqttPahoClientFactory mqttPahoClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true); //设置新会话
options.setUserName(mqttPropertiesConfig.getUsername());
options.setPassword(mqttPropertiesConfig.getPassword().toCharArray());
options.setServerURIs(new String[]{mqttPropertiesConfig.getUrl()});
options.setCleanSession(true); // 设置新会话
// 修复用户名为null时的空指针异常
String username = mqttPropertiesConfig.getUsername();
if (username != null) {
options.setUserName(username);
}
// 修复密码为null时的空指针异常
String password = mqttPropertiesConfig.getPassword();
if (password != null) {
options.setPassword(password.toCharArray());
}
// 修复URL为null时的空指针异常
String url = mqttPropertiesConfig.getUrl();
if (url != null) {
options.setServerURIs(new String[]{url});
}
options.setAutomaticReconnect(true); // 启用自动重连
options.setConnectionTimeout(10); // 设置连接超时时间
options.setKeepAliveInterval(60); // 设置心跳间隔
factory.setConnectionOptions(options);
return factory;
}
}

View File

@ -1,15 +1,9 @@
package com.fuyuanshen.system.mqtt.config;
package com.fuyuanshen.global.mqtt.config;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;
/**
* @Author: HarryLin
* @Date: 2025/3/20 17:06
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@MessagingGateway(defaultRequestChannel = "mqttOutboundChannel")
public interface MqttGateway {
public abstract void sendMsgToMqtt(@Header(value = MqttHeaders.TOPIC) String topic, String payload);

View File

@ -1,8 +1,9 @@
package com.fuyuanshen.system.mqtt.config;
package com.fuyuanshen.global.mqtt.config;
import cn.hutool.core.lang.UUID;
import com.fuyuanshen.system.mqtt.receiver.ReceiverMessageHandler;
import com.fuyuanshen.global.mqtt.receiver.ReceiverMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -15,12 +16,7 @@ import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
/**
* @Author: HarryLin
* @Date: 2025/3/20 14:54
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Configuration
public class MqttInboundConfiguration {
@Autowired
@ -43,11 +39,17 @@ public class MqttInboundConfiguration {
public MessageProducer messageProducer(){
// 生成一个不重复的随机数
String clientId = mqttPropertiesConfig.getSubClientId() + "_" + UUID.fastUUID();
// 修复URL为null时的空指针异常
String url = mqttPropertiesConfig.getUrl();
if (url == null) {
throw new IllegalStateException("MQTT服务器URL未配置");
}
String subTopic = mqttPropertiesConfig.getSubTopic();
MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter(
mqttPropertiesConfig.getUrl(),
url,
clientId,
mqttPahoClientFactory,
mqttPropertiesConfig.getSubTopic().split(",")
subTopic.split(",")
);
mqttPahoMessageDrivenChannelAdapter.setQos(1);
mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter());
@ -60,4 +62,10 @@ public class MqttInboundConfiguration {
public MessageHandler messageHandler(){
return receiverMessageHandler;
}
// @Bean
// @ServiceActivator(inputChannel = "messageInboundChannel") // 确保通道名称正确
// public MessageHandler deviceAlarmMessageHandler() {
// return new DeviceAlrmMessageHandler();
// }
}

View File

@ -1,4 +1,4 @@
package com.fuyuanshen.system.mqtt.config;
package com.fuyuanshen.global.mqtt.config;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
@ -12,20 +12,17 @@ import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
/**
* @Author: HarryLin
* @Date: 2025/3/20 15:46
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Configuration
@Slf4j
public class MqttOutboundConfiguration {
@Autowired
private MqttPropertiesConfig mqttPropertiesConfig;
@Autowired
private MqttPahoClientFactory mqttPahoClientFactory;
// 消息通道
@Bean
public MessageChannel mqttOutboundChannel(){
@ -38,13 +35,19 @@ public class MqttOutboundConfiguration {
@ServiceActivator(inputChannel = "mqttOutboundChannel") // 指定处理器针对哪个通道的消息进行处理
public MessageHandler mqttOutboundMessageHandler(){
String clientId = mqttPropertiesConfig.getPubClientId() + "_" + UUID.fastUUID();
// 修复URL为null时的空指针异常
String url = mqttPropertiesConfig.getUrl();
if (url == null) {
throw new IllegalStateException("MQTT服务器URL未配置");
}
MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(
mqttPropertiesConfig.getUrl(),
url,
clientId,
mqttPahoClientFactory
);
mqttPahoMessageHandler.setDefaultQos(1);
mqttPahoMessageHandler.setDefaultTopic("B/#");
mqttPahoMessageHandler.setDefaultTopic(mqttPropertiesConfig.getPubTopic());
mqttPahoMessageHandler.setAsync(true);
return mqttPahoMessageHandler;
}

View File

@ -1,15 +1,10 @@
package com.fuyuanshen.system.mqtt.config;
package com.fuyuanshen.global.mqtt.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author: HarryLin
* @Date: 2025/3/20 14:32
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Data
@ConfigurationProperties(prefix = "mqtt")
@Component
@ -19,6 +14,8 @@ public class MqttPropertiesConfig {
private String url;
private String subClientId;
private String subTopic;
private String subTopic2;
private String pubClientId;
private String pubTopic;
private String pubTopic2;
}

View File

@ -0,0 +1,68 @@
package com.fuyuanshen.global.mqtt.config;
import cn.hutool.core.lang.UUID;
import com.fuyuanshen.global.mqtt.receiver.NewReceiverMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
@Configuration
@Slf4j
public class NewMqttInboundConfiguration {
@Autowired
private MqttPropertiesConfig mqttPropertiesConfig;
@Autowired
private MqttPahoClientFactory mqttPahoClientFactory;
@Autowired
private NewReceiverMessageHandler receiverMessageHandler2;
//消息通道
@Bean
public MessageChannel messageInboundChannel2(){
return new DirectChannel();
}
/**
* 配置入站适配器
* 作用: 设置订阅主题,以及指定消息的通道 等相关属性
* */
@Bean
public MessageProducer messageProducer2(){
// 生成一个不重复的随机数
String clientId = mqttPropertiesConfig.getSubClientId() + "_" + UUID.fastUUID();
String subTopic = mqttPropertiesConfig.getSubTopic2();
log.info("订阅主题:{}", subTopic);
MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter(
mqttPropertiesConfig.getUrl(),
clientId,
mqttPahoClientFactory,
subTopic.split(",")
);
mqttPahoMessageDrivenChannelAdapter.setQos(1);
mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter());
mqttPahoMessageDrivenChannelAdapter.setOutputChannel(messageInboundChannel2());
return mqttPahoMessageDrivenChannelAdapter;
}
/** 指定处理消息来自哪个通道 */
@Bean
@ServiceActivator(inputChannel = "messageInboundChannel2")
public MessageHandler messageHandler2(){
return receiverMessageHandler2;
}
// @Bean
// @ServiceActivator(inputChannel = "messageInboundChannel") // 确保通道名称正确
// public MessageHandler deviceAlarmMessageHandler() {
// return new DeviceAlrmMessageHandler();
// }
}

View File

@ -0,0 +1,46 @@
package com.fuyuanshen.global.mqtt.config;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
@Configuration
@Slf4j
public class NewMqttOutboundConfiguration {
@Autowired
private MqttPropertiesConfig mqttPropertiesConfig;
@Autowired
private MqttPahoClientFactory mqttPahoClientFactory;
// 消息通道
@Bean
public MessageChannel mqttOutboundChannel2(){
return new DirectChannel();
}
/** 配置出站消息处理器 */
@Bean
@ServiceActivator(inputChannel = "mqttOutboundChannel2") // 指定处理器针对哪个通道的消息进行处理
public MessageHandler mqttOutboundMessageHandler2(){
String clientId = mqttPropertiesConfig.getPubClientId() + "_" + UUID.fastUUID();
MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(
mqttPropertiesConfig.getUrl(),
clientId,
mqttPahoClientFactory
);
mqttPahoMessageHandler.setDefaultQos(1);
mqttPahoMessageHandler.setDefaultTopic(mqttPropertiesConfig.getPubTopic2());
mqttPahoMessageHandler.setAsync(true);
return mqttPahoMessageHandler;
}
}

View File

@ -0,0 +1,57 @@
package com.fuyuanshen.global.mqtt.constants;
public class DeviceRedisKeyConstants {
public static final String DEVICE_KEY_PREFIX = "device:";
// 设备上报状态
public static final String DEVICE_STATUS_KEY_PREFIX = ":status";
// 在线状态
public static final String DEVICE_ONLINE_STATUS_KEY_PREFIX = ":onlineStatus";
// 设备状态信息存储到Redis中
public static final String DEVICE_LOCATION_KEY_PREFIX = ":location";
// 存储到一个列表中,保留历史位置信息
public static final String DEVICE_LOCATION_HISTORY_KEY_PREFIX = ":location:history";
// 存储设备活跃上报信息
public static final String DEVICE_ACTIVE_REPORTING_KEY_PREFIX = ":activeReporting";
// 存储设备人员信息
public static final String DEVICE_PERSONNEL_INFO_KEY_PREFIX = ":personnelInfo";
// 存储设备发送消息
public static final String DEVICE_SEND_MESSAGE_KEY_PREFIX = ":sendMessage";
// 存储设备启动logo
public static final String DEVICE_BOOT_LOGO_KEY_PREFIX = ":bootLogo";
/**
* 灯模式
*/
public static final String DEVICE_LIGHT_MODE_KEY_PREFIX = ":lightMode";
/**
* 亮度模式
*/
public static final String DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX = ":lightBrightness";
/**
* 激光模式
*/
public static final String DEVICE_LASER_MODE_KEY_PREFIX = ":laserMode";
/**
* 地图逆地理编码
*/
public static final String DEVICE_MAP_REVERSE_GEOCODING_KEY_PREFIX = ":mapReverseGeocoding";
/**
* 告警
*/
public static final String DEVICE_ALARM_KEY_PREFIX = ":alarm";
/**
* 告警信息
*/
public static final String DEVICE_ALARM_MESSAGE_KEY_PREFIX = ":alarmMessage";
}

View File

@ -0,0 +1,54 @@
package com.fuyuanshen.global.mqtt.constants;
/**
* 设备命令类型常量
* Device Command Type Constants
*/
public class LightingCommandTypeConstants {
/**
* 灯光模式 (Light Mode)
*/
public static final String LIGHT_MODE = "Light_1";
/**
* 人员信息 (Personnel Information)
*/
public static final String PERSONNEL_INFO = "Light_2";
/**
* 开机LOGO (Boot Logo)
*/
public static final String BOOT_LOGO = "Light_3";
/**
* 激光灯 (Laser Light)
*/
public static final String LASER_LIGHT = "Light_4";
/**
* 主灯亮度 (Main Light Brightness)
*/
public static final String MAIN_LIGHT_BRIGHTNESS = "Light_5";
/**
* 设备发送消息
*/
public static final String SEND_MESSAGE = "Light_6";
/**
* 报警模式
*/
public static final String ALARM_MESSAGE = "Light_7";
/**
* 定位数据 (Location Data)
*/
public static final String LOCATION_DATA = "Light_11";
/**
* 主动上报设备数据 (Active Reporting Device Data)
*/
public static final String ACTIVE_REPORTING_DEVICE_DATA = "Light_12";
}

View File

@ -1,9 +1,8 @@
package com.fuyuanshen.system.mqtt.constants;
package com.fuyuanshen.global.mqtt.constants;
public interface MqttConstants {
/**
* 全局发布消息的key
*/
@ -13,4 +12,6 @@ public interface MqttConstants {
* 全局订阅消息的key
*/
String GLOBAL_SUB_KEY = "A/";
String GLOBAL_PUB_KEY2 = "command/";
}

View File

@ -0,0 +1,27 @@
package com.fuyuanshen.global.mqtt.constants;
/**
* 租户常量定义类
* 包含系统中使用的各种租户标识
*
* @author: 默苍璃
* @date: 2025-08-05 10:46
*/
public class TenantsConstant {
/**
* 晶全租户
*/
public static final String JING_QUAN = "014443";
/**
* 富源晟租户
*/
public static final String FU_YUAN_SHENG = "894078";
/**
* 管理员租户
*/
public static final String ADMIN = "000000";
}

View File

@ -0,0 +1,20 @@
package com.fuyuanshen.global.mqtt.constants;
public class XingHanCommandTypeConstants {
/**
* 星汉设备主动上报数据 (XingHan Device Data)
*/
public static final String XingHan_DEVICE_DATA = "Light_101";
/**
* 星汉开机LOGO (XingHan Boot Logo)
*/
public static final String XingHan_BOOT_LOGO = "Light_102";
/**
* 星汉设备发送消息 (XingHan send msg)
*/
public static final String XingHan_ESEND_MSG = "Light_103";
/**
* 星汉设备发送紧急通知 (XingHan break news)
*/
public static final String XingHan_BREAK_NEWS = "Light_104";
}

View File

@ -0,0 +1,82 @@
package com.fuyuanshen.global.mqtt.enums;
/**
* 设备功能类型枚举
* 基于AppDeviceBJQ6075Controller中的功能注释1-9设计
*/
public enum DeviceFunctionType6075 {
/**
* 人员信息登记
*/
REGISTER_PERSON_INFO(1, "REGISTER_PERSON_INFO", "人员信息登记"),
/**
* 发送信息
*/
SEND_MESSAGE(2, "SEND_MESSAGE", "发送信息"),
/**
* 发送报警信息
*/
SEND_ALARM_MESSAGE(3, "SEND_ALARM_MESSAGE", "发送报警信息"),
/**
* 上传设备logo图片
*/
UPLOAD_LOGO(4, "UPLOAD_LOGO", "上传设备logo图片"),
/**
* 灯光模式(主光模式)
* 0关闭灯光1强光2超强光, 3工作光, 4节能光5爆闪6SOS
*/
LIGHT_MODE(5, "LIGHT_MODE", "灯光模式"),
/**
* 灯光模式(辅光模式)
* 0关闭灯光1泛光2泛光爆闪, 3警示灯, 4警示灯/泛光)
*/
AUXILIARY_LIGHT_MODE(6, "AUXILIARY_LIGHT_MODE", "辅光模式"),
/**
* 灯光亮度设置
*/
LIGHT_BRIGHTNESS(7, "LIGHT_BRIGHTNESS", "灯光亮度设置"),
/**
* 激光模式设置
*/
LASER_MODE(8, "LASER_MODE", "激光模式设置"),
/**
* 声光报警模式设置
*/
SOUND_AND_LIGHT_ALARM(9, "SOUND_AND_LIGHT_ALARM", "声光报警模式设置");
private final int number;
private final String code;
private final String description;
DeviceFunctionType6075(int number, String code, String description) {
this.number = number;
this.code = code;
this.description = description;
}
public int getNumber() {
return number;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return code;
}
}

View File

@ -0,0 +1,136 @@
package com.fuyuanshen.global.mqtt.handler;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
import com.fuyuanshen.global.mqtt.service.IotMqttService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* IoT设备MQTT消息处理器
* 用于处理设备上报的数据和响应消息
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class IotMqttMessageHandler {
private final IotMqttService iotMqttService;
/**
* 处理MQTT消息
*
* @param topic 主题
* @param payload 消息内容
*/
public void handleMessage(String topic, String payload) {
try {
// 解析主题
MqttTopicInfo topicInfo = parseTopic(topic);
if (topicInfo == null) {
log.warn("无法解析MQTT主题: topic={}", topic);
return;
}
// 解析消息内容
JSONObject message = JSON.parseObject(payload);
// 根据主题类型处理消息
switch (topicInfo.getOperation()) {
case "command":
// 处理下发指令设备端不会主动发送command类型消息
log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
break;
case "status":
// 处理设备对指令的响应
iotMqttService.handleCommandResponse(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
message);
break;
case "report":
// 处理设备主动上报的数据
handleDeviceReport(topicInfo, message);
break;
default:
log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
break;
}
} catch (Exception e) {
log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
}
}
/**
* 解析MQTT主题
*
* @param topic 主题字符串
* @return 主题信息对象
*/
MqttTopicInfo parseTopic(String topic) {
if (topic == null || topic.isEmpty()) {
return null;
}
String[] parts = topic.split("/");
if (parts.length != 4) {
return null;
}
MqttTopicInfo info = new MqttTopicInfo();
info.setOperation(parts[0]);
info.setTenantCode(parts[1]);
info.setDeviceType(parts[2]);
info.setImei(parts[3]);
return info;
}
/**
* 处理设备上报数据
*
* @param topicInfo 主题信息
* @param message 消息内容
*/
private void handleDeviceReport(MqttTopicInfo topicInfo, JSONObject message) {
// 获取时间戳
Long timestamp = message.getLong("timestamp");
// 处理批量数据上报
if (message.containsKey("batch")) {
JSONObject batchData = message.getJSONObject("batch");
iotMqttService.handleBatchReport(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
batchData,
timestamp);
}
// 处理单个数据上报
else if (message.containsKey("sensor") && message.containsKey("value")) {
String sensor = message.getString("sensor");
Object value = message.get("value");
iotMqttService.handleSingleReport(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
sensor,
value,
timestamp);
}
// 处理其他格式的数据
else {
// 将整个消息作为批量数据处理
iotMqttService.handleBatchReport(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
message,
timestamp);
}
}
}

View File

@ -0,0 +1,71 @@
package com.fuyuanshen.global.mqtt.handler;
import com.alibaba.fastjson2.JSON;
import com.fuyuanshen.global.mqtt.base.MqttMessage;
import com.fuyuanshen.global.mqtt.service.MqttMessageService;
import com.fuyuanshen.global.mqtt.utils.MqttTopicUtils;
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* MQTT消息处理器
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class MqttMessageHandler {
private final MqttMessageService mqttMessageService;
/**
* 处理MQTT消息
* @param topic 主题
* @param payload 消息内容
*/
public void handleMessage(String topic, String payload) {
try {
// 解析主题
MqttTopicInfo topicInfo = MqttTopicUtils.parseTopic(topic);
if (topicInfo == null) {
log.warn("无法解析MQTT主题: topic={}", topic);
return;
}
// 解析消息内容
MqttMessage message = JSON.parseObject(payload, MqttMessage.class);
// 根据主题类型处理消息
switch (topicInfo.getOperation()) {
case "command":
// 处理下发指令设备端不会主动发送command类型消息
log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
break;
case "status":
// 处理设备对指令的响应
mqttMessageService.handleCommandResponse(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
message);
break;
case "report":
// 处理设备主动上报的数据
mqttMessageService.handleDeviceReport(
topicInfo.getTenantCode(),
topicInfo.getDeviceType(),
topicInfo.getImei(),
message);
break;
default:
log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
break;
}
} catch (Exception e) {
log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
}
}
}

View File

@ -0,0 +1,105 @@
package com.fuyuanshen.global.mqtt.listener;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.time.Duration;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_TIMEOUT_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
@Component
@Slf4j
public class RedisKeyExpirationListener implements MessageListener {
@Autowired
@Qualifier("threadPoolTaskExecutor")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private LockTemplate lockTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
String expiredKey = new String(message.getBody());
if (expiredKey.startsWith(FUNCTION_ACCESS_KEY)) {
String element = expiredKey.substring(FUNCTION_ACCESS_KEY.length());
handleFunctionAccessExpired(element);
}
if(expiredKey.endsWith(DEVICE_ONLINE_STATUS_KEY_PREFIX)) {
threadPoolTaskExecutor.execute(() -> {
log.info("设备离线:{}", expiredKey);
String element = expiredKey.substring(GlobalConstants.GLOBAL_REDIS_KEY.length() + DEVICE_KEY_PREFIX.length(), expiredKey.length() - DEVICE_ONLINE_STATUS_KEY_PREFIX.length());
// 构造设备锁键
String deviceLockKey = GlobalConstants.GLOBAL_REDIS_KEY + ":device_lock:" + element;
// 尝试获取Redis锁
LockInfo lockInfo = lockTemplate.lock(deviceLockKey, 30000L, 5000L, RedissonLockExecutor.class); // 30秒过期
if (lockInfo != null) {
try {
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ message + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
// String deviceOnlineStatusRedis = RedisUtils.getCacheObject(deviceOnlineStatusRedisKey);
// if(StringUtils.isBlank(deviceOnlineStatusRedis)){
// UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
// deviceUpdateWrapper.eq("device_imei", element);
// deviceUpdateWrapper.set("online_status", 0);
// deviceMapper.update(deviceUpdateWrapper);
// }else{
// RedisUtils.deleteObject(deviceOnlineStatusRedisKey);
// }
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("device_imei", element);
deviceUpdateWrapper.set("online_status", 0);
deviceMapper.update(deviceUpdateWrapper);
String deviceOnlineStatusRedis = RedisUtils.getCacheObject(deviceOnlineStatusRedisKey);
if(StringUtils.isNotBlank(deviceOnlineStatusRedis)){
RedisUtils.deleteObject(deviceOnlineStatusRedisKey);
}
} finally {
//释放锁
lockTemplate.releaseLock(lockInfo);
}
} else {
log.warn("无法获取设备锁,跳过设备离线处理: {}", element);
}
});
}
}
/**
* 访问key过期事件
* @param element 批次ID
*/
private void handleFunctionAccessExpired(String element) {
RedisUtils.setCacheObject(FUNCTION_ACCESS_TIMEOUT_KEY + element, FunctionAccessStatus.TIMEOUT.getCode(), Duration.ofSeconds(30L));
}
}

View File

@ -0,0 +1,25 @@
package com.fuyuanshen.global.mqtt.listener.config;
import com.fuyuanshen.global.mqtt.listener.RedisKeyExpirationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory,
RedisKeyExpirationListener redisKeyExpirationListener) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// 监听过期事件
container.addMessageListener(redisKeyExpirationListener, new PatternTopic("__keyevent@*__:expired"));
return container;
}
}

View File

@ -0,0 +1,96 @@
package com.fuyuanshen.global.mqtt.listener.domain;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
/**
* 功能访问状态对象
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FunctionAccessResult {
/**
* 状态码
*/
private String status;
/**
* 消息描述
*/
private String message;
/**
* 时间戳
*/
private Long timestamp;
/**
* 设备IMEI可选
*/
private String deviceImei;
/**
* 批次ID可选
*/
private String batchId;
public FunctionAccessResult(String status, String message) {
this.status = status;
this.message = message;
this.timestamp = System.currentTimeMillis();
}
/**
* 创建失败状态对象
* @param message 消息
* @return FunctionAccessResult
*/
public static FunctionAccessResult failed(String message) {
return new FunctionAccessResult("FAILED", message);
}
/**
* 创建成功状态对象
* @param message 消息
* @return FunctionAccessResult
*/
public static FunctionAccessResult ok(String message) {
return new FunctionAccessResult("OK", message);
}
/**
* 创建超时状态对象
* @param message 消息
* @return FunctionAccessResult
*/
public static FunctionAccessResult timeout(String message) {
return new FunctionAccessResult("TIMEOUT", message);
}
/**
* 判断是否为失败状态
* @return boolean
*/
public boolean isFailed() {
return "FAILED".equals(this.status);
}
/**
* 判断是否为成功状态
* @return boolean
*/
public boolean isOk() {
return "OK".equals(this.status);
}
/**
* 判断是否为超时状态
* @return boolean
*/
public boolean isTimeout() {
return "TIMEOUT".equals(this.status);
}
}

View File

@ -0,0 +1,62 @@
package com.fuyuanshen.global.mqtt.listener.domain;
/**
* 功能访问状态枚举
*/
public enum FunctionAccessStatus {
/**
* 失败状态
*/
FAILED("FAILED", "失败"),
/**
* 成功状态
*/
OK("OK", "成功"),
/**
* 激活中状态
*/
ACTIVE("ACTIVE", "处理中"),
/**
* 超时状态
*/
TIMEOUT("TIMEOUT", "超时");
private final String code;
private final String description;
FunctionAccessStatus(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
/**
* 根据代码获取状态枚举
* @param code 状态代码
* @return 对应的状态枚举
*/
public static FunctionAccessStatus fromCode(String code) {
for (FunctionAccessStatus status : FunctionAccessStatus.values()) {
if (status.getCode().equals(code)) {
return status;
}
}
throw new IllegalArgumentException("未知的状态代码: " + code);
}
@Override
public String toString() {
return code;
}
}

View File

@ -1,20 +1,22 @@
package com.fuyuanshen.system.mqtt.publish;
package com.fuyuanshen.global.mqtt.publish;
import cn.dev33.satoken.annotation.SaIgnore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/")
@RequestMapping("/api")
@SaIgnore
@Slf4j
public class DeviceDataController {
@Autowired
private MqttClientTest mqttClientTest;
// @PostMapping("/{deviceId}/command")
@GetMapping("/command")
public ResponseEntity<String> sendCommand() {
mqttClientTest.sendMsg();

View File

@ -1,7 +1,7 @@
package com.fuyuanshen.system.mqtt.publish;
package com.fuyuanshen.global.mqtt.publish;
import com.fuyuanshen.system.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -13,10 +13,10 @@ public class MqttClientTest {
private MqttGateway mqttGateway;
public void sendMsg() {
mqttGateway.sendMsgToMqtt("worker/location/1", "hello mqtt spring boot");
mqttGateway.sendMsgToMqtt("command/894078/HBY670/864865082081523", "hello mqtt spring boot");
log.info("message is send");
mqttGateway.sendMsgToMqtt("worker/alert/2", "hello mqtt spring boot2");
mqttGateway.sendMsgToMqtt("report/894078/HBY670/864865082081523", "hello mqtt spring boot2");
log.info("message is send2");
}
}

View File

@ -1,17 +1,12 @@
package com.fuyuanshen.system.mqtt.publish;
package com.fuyuanshen.global.mqtt.publish;
import com.fuyuanshen.system.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
/**
* @Author: HarryLin
* @Date: 2025/3/20 16:16
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Service
public class MqttMessageSender {
@Autowired

View File

@ -0,0 +1,279 @@
package com.fuyuanshen.global.mqtt.receiver;
import cn.hutool.core.lang.Dict;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.base.MqttRuleEngine;
import com.fuyuanshen.global.mqtt.base.MqttXinghanCommandType;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Objects;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 6075
*
* @author: 默苍璃
* @date: 2025-11-05 17:41
*/
@Service
@Slf4j
public class DeviceMessageHandler implements MessageHandler {
@Autowired
private MqttRuleEngine ruleEngine;
@Override
public void handleMessage(Message<?> message) throws MessagingException {
Object payload = message.getPayload();
MessageHeaders headers = message.getHeaders();
String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();
String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
log.info("MQTT payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
payload, receivedTopic, receivedQos, timestamp);
Dict payloadDict = JsonUtils.parseMap(payload.toString());
if (receivedTopic == null || payloadDict == null) {
return;
}
// 解析设备IMEI
String[] subStr = receivedTopic.split("/");
String deviceImei = subStr[1];
// 处理设备在线状态
handleDeviceOnlineStatus(deviceImei);
// 处理不同类型的设备信息
processDeviceInformation(payloadDict, deviceImei);
// 执行规则引擎处理
executeRuleEngine(payloadDict, deviceImei);
}
/**
* 处理设备在线状态
*/
private void handleDeviceOnlineStatus(String deviceImei) {
if (StringUtils.isNotBlank(deviceImei)) {
// 添加去重队列
String queueKey = MqttMessageQueueConstants.MQTT_MESSAGE_QUEUE_KEY;
String dedupKey = MqttMessageQueueConstants.MQTT_MESSAGE_DEDUP_KEY;
RedisUtils.offerDeduplicated(queueKey, dedupKey, deviceImei, Duration.ofSeconds(900));
// 设置设备在线状态
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY +
DEVICE_KEY_PREFIX + deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(360));
}
}
/**
* 处理不同类型的设备信息
*/
private void processDeviceInformation(Dict payloadDict, String deviceImei) {
// 开机画面
if (payloadDict.containsKey("bootScreen")) {
handleBootScreen(payloadDict, deviceImei);
}
// 人员信息
if (payloadDict.containsKey("personInfo")) {
handlePersonInfo(payloadDict, deviceImei);
}
// 设备信息
if (payloadDict.containsKey("deviceInfo")) {
handleDeviceInfo(payloadDict, deviceImei);
}
// 经纬度
if (payloadDict.containsKey("latitude") && payloadDict.containsKey("longitude")) {
handleLocation(payloadDict, deviceImei);
}
// 电子地图
if (payloadDict.containsKey("mapData")) {
handleMapData(payloadDict, deviceImei);
}
// 电池电量
if (payloadDict.containsKey("batteryLevel")) {
handleBatteryLevel(payloadDict, deviceImei);
}
// 开启/关闭状态
if (payloadDict.containsKey("powerState")) {
handlePowerState(payloadDict, deviceImei);
}
// 海拔高度
if (payloadDict.containsKey("altitude")) {
handleAltitude(payloadDict, deviceImei);
}
// 相对高度
if (payloadDict.containsKey("relativeHeight")) {
handleRelativeHeight(payloadDict, deviceImei);
}
// 群呼/单呼
if (payloadDict.containsKey("callType")) {
handleCallType(payloadDict, deviceImei);
}
// 文字信息
if (payloadDict.containsKey("textMessage")) {
handleTextMessage(payloadDict, deviceImei);
}
}
/**
* 处理开机画面
*/
private void handleBootScreen(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的开机画面信息", deviceImei);
// 实现具体的开机画面处理逻辑
}
/**
* 处理人员信息
*/
private void handlePersonInfo(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的人员信息", deviceImei);
// 实现具体的人员信息处理逻辑
}
/**
* 处理设备信息
*/
private void handleDeviceInfo(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的设备信息", deviceImei);
// 实现具体的设备信息处理逻辑
}
/**
* 处理位置信息
*/
private void handleLocation(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的位置信息: 纬度={}, 经度={}",
deviceImei, payloadDict.getStr("latitude"), payloadDict.getStr("longitude"));
// 实现具体的位置信息处理逻辑
}
/**
* 处理电子地图数据
*/
private void handleMapData(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的电子地图数据", deviceImei);
// 实现具体的电子地图数据处理逻辑
}
/**
* 处理电池电量
*/
private void handleBatteryLevel(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的电池电量: {}", deviceImei, payloadDict.getStr("batteryLevel"));
// 实现具体的电池电量处理逻辑
}
/**
* 处理开关状态
*/
private void handlePowerState(Dict payloadDict, String deviceImei) {
String powerState = payloadDict.getStr("powerState");
log.info("处理设备{}的开关状态: {}", deviceImei, powerState);
// 实现具体的开关状态处理逻辑
}
/**
* 处理海拔高度
*/
private void handleAltitude(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的海拔高度: {}", deviceImei, payloadDict.getStr("altitude"));
// 实现具体的海拔高度处理逻辑
}
/**
* 处理相对高度
*/
private void handleRelativeHeight(Dict payloadDict, String deviceImei) {
log.info("处理设备{}的相对高度: {}", deviceImei, payloadDict.getStr("relativeHeight"));
// 实现具体的相对高度处理逻辑
}
/**
* 处理呼叫类型
*/
private void handleCallType(Dict payloadDict, String deviceImei) {
String callType = payloadDict.getStr("callType");
log.info("处理设备{}的呼叫类型: {}", deviceImei, callType);
// 实现具体的呼叫类型处理逻辑
}
/**
* 处理文字信息
*/
private void handleTextMessage(Dict payloadDict, String deviceImei) {
String textMessage = payloadDict.getStr("textMessage");
log.info("处理设备{}的文字信息: {}", deviceImei, textMessage);
// 实现具体的文字信息处理逻辑
}
/**
* 执行规则引擎处理
*/
private void executeRuleEngine(Dict payloadDict, String deviceImei) {
String state = payloadDict.getStr("state");
Object[] convertArr = ImageToCArrayConverter.convertByteStringToMixedObjectArray(state);
if (convertArr.length > 0) {
Byte val1 = (Byte) convertArr[0];
MqttRuleContext context = new MqttRuleContext();
context.setCommandType(val1);
context.setConvertArr(convertArr);
context.setDeviceImei(deviceImei);
context.setPayloadDict(payloadDict);
boolean ruleExecuted = ruleEngine.executeRule(context);
if (!ruleExecuted) {
log.warn("未找到匹配的规则来处理命令类型: {}", val1);
}
}
/* ===== 追加:根据报文内容识别格式并统一解析 ===== */
int intType = MqttXinghanCommandType.computeVirtualCommandType(payloadDict);
if (intType > 0) {
MqttRuleContext newCtx = new MqttRuleContext();
newCtx.setCommandType((byte) intType);
newCtx.setDeviceImei(deviceImei);
newCtx.setPayloadDict(payloadDict);
boolean ok = ruleEngine.executeRule(newCtx);
if (!ok) {
log.warn("新规则引擎未命中, imei={}", deviceImei);
}
}
}
}

View File

@ -0,0 +1,125 @@
package com.fuyuanshen.global.mqtt.receiver;
import cn.hutool.core.lang.Dict;
import com.baomidou.lock.LockTemplate;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleEngine;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
@Service
@Slf4j
public class NewReceiverMessageHandler implements MessageHandler {
@Autowired
private NewMqttRuleEngine newRuleEngine;
@Override
public void handleMessage(Message<?> message) throws MessagingException {
Object payload = message.getPayload();
MessageHeaders headers = message.getHeaders();
String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();
String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
log.info("MQTT2 payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
payload, receivedTopic, receivedQos, timestamp);
Dict payloadDict = JsonUtils.parseMap(payload.toString());
if (receivedTopic == null || payloadDict == null) {
return;
}
String imei = payloadDict.getStr("imei");
String funcType = payloadDict.getStr("funcType");
// 执行业务逻辑
if(StringUtils.isNotBlank(imei)){
String queueKey = MqttMessageQueueConstants.MQTT_MESSAGE_QUEUE_KEY;
String dedupKey = MqttMessageQueueConstants.MQTT_MESSAGE_DEDUP_KEY;
RedisUtils.offerDeduplicated(queueKey,dedupKey,imei, Duration.ofSeconds(900));
//在线状态
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ imei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(360));
}
String[] topicArr = receivedTopic.split("/");
NewMqttRuleContext context = new NewMqttRuleContext();
context.setCommandType(topicArr[2]+"_"+funcType);
context.setDeviceImei(imei);
context.setPayloadDict(payloadDict);
boolean ruleExecuted = newRuleEngine.executeRule(context);
if (!ruleExecuted) {
log.warn("未找到匹配的规则来处理命令类型: {}", topicArr[2] + " : " +funcType);
}
// final LockInfo lockInfo = lockTemplate.lock(GlobalConstants.GLOBAL_REDIS_KEY + lockKey + imei, 100L, 3000L, RedissonLockExecutor.class);
// if (null == lockInfo) {
// log.info("MQTT3业务处理中,请稍后再试:funcType=>{},imei=>{}",funcType,imei);
// return;
// }
//// 获取锁成功,处理业务
// try {
// if(StringUtils.isNotBlank(imei)){
// String queueKey = MqttMessageQueueConstants.MQTT_MESSAGE_QUEUE_KEY;
// String dedupKey = MqttMessageQueueConstants.MQTT_MESSAGE_DEDUP_KEY;
// RedisUtils.offerDeduplicated(queueKey,dedupKey,imei, Duration.ofSeconds(900));
// //在线状态
// String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ imei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
// RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(360));
// }
//
// String[] topicArr = receivedTopic.split("/");
//
// NewMqttRuleContext context = new NewMqttRuleContext();
// context.setCommandType(topicArr[2]+"_"+funcType);
// context.setDeviceImei(imei);
// context.setPayloadDict(payloadDict);
//
// boolean ruleExecuted = newRuleEngine.executeRule(context);
//
// if (!ruleExecuted) {
// log.warn("未找到匹配的规则来处理命令类型: {}", topicArr[2] + " : " +funcType);
// }
// } finally {
// //释放锁
// lockTemplate.releaseLock(lockInfo);
// }
/* ===== 追加:根据报文内容识别格式并统一解析 ===== */
// int intType = MqttXinghanCommandType.computeVirtualCommandType(payloadDict);
// if (intType > 0) {
// MqttRuleContext newCtx = new MqttRuleContext();
// String commandType = "Light_"+intType;
// newCtx.setCommandType(commandType);
// newCtx.setDeviceImei(imei);
// newCtx.setPayloadDict(payloadDict);
//
// boolean ok = ruleEngine.executeRule(newCtx);
// if (!ok) {
// log.warn("新规则引擎未命中, imei={}", imei);
// }
// }
}
}

View File

@ -0,0 +1,120 @@
package com.fuyuanshen.global.mqtt.receiver;
import cn.hutool.core.lang.Dict;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.base.MqttRuleEngine;
import com.fuyuanshen.global.mqtt.base.MqttXinghanCommandType;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
@Service
@Slf4j
public class ReceiverMessageHandler implements MessageHandler {
@Autowired
private MqttRuleEngine ruleEngine;
@Override
public void handleMessage(Message<?> message) throws MessagingException {
Object payload = message.getPayload();
MessageHeaders headers = message.getHeaders();
String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();
String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
log.info("MQTT payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
payload, receivedTopic, receivedQos, timestamp);
Dict payloadDict = JsonUtils.parseMap(payload.toString());
if (receivedTopic == null || payloadDict == null) {
return;
}
String[] subStr = receivedTopic.split("/");
String deviceImei = subStr[1];
RedissonClient client = RedisUtils.getClient();
String lockKey = "mqtt:consumer:lock:";
String KEY = GlobalConstants.GLOBAL_REDIS_KEY + lockKey + deviceImei;
RLock lock = client.getLock(KEY);
try {
// 尝试获取锁,
boolean isLocked = lock.tryLock(60, 3000, TimeUnit.MILLISECONDS);
if (isLocked) {
String state = payloadDict.getStr("state");
Object[] convertArr = ImageToCArrayConverter.convertByteStringToMixedObjectArray(state);
if(StringUtils.isNotBlank(deviceImei)){
String queueKey = MqttMessageQueueConstants.MQTT_MESSAGE_QUEUE_KEY;
String dedupKey = MqttMessageQueueConstants.MQTT_MESSAGE_DEDUP_KEY;
RedisUtils.offerDeduplicated(queueKey,dedupKey,deviceImei, Duration.ofSeconds(900));
//在线状态
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(360));
}
if (convertArr.length > 0) {
Byte val1 = (Byte) convertArr[0];
MqttRuleContext context = new MqttRuleContext();
context.setCommandType(val1);
context.setConvertArr(convertArr);
context.setDeviceImei(deviceImei);
context.setPayloadDict(payloadDict);
boolean ruleExecuted = ruleEngine.executeRule(context);
if (!ruleExecuted) {
log.warn("未找到匹配的规则来处理命令类型: {}", val1);
}
}
/* ===== 追加:根据报文内容识别格式并统一解析 ===== */
int intType = MqttXinghanCommandType.computeVirtualCommandType(payloadDict);
if (intType > 0) {
MqttRuleContext newCtx = new MqttRuleContext();
newCtx.setCommandType((byte) intType);
newCtx.setDeviceImei(deviceImei);
newCtx.setPayloadDict(payloadDict);
boolean ok = ruleEngine.executeRule(newCtx);
if (!ok) {
log.warn("新规则引擎未命中, imei={}", deviceImei);
}
}
}else{
log.warn("MQTT获取锁失败请稍后再试");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// 释放锁
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}

View File

@ -0,0 +1,97 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX;
/**
* 主动上报设备数据命令处理
* "第1位为12表示设备主动上报设备硬件状态第2为表示当时设备主灯档位第3位表示当时激光灯档位第4位电量百分比第5位为充电状态0没有充电1正在充电2为已充满
* 第6位200代表电池剩余续航时间200分钟"
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqActiveReportingDeviceDataRule implements MqttMessageRule {
@Override
public String getCommandType() {
return LightingCommandTypeConstants.ACTIVE_REPORTING_DEVICE_DATA;
}
@Override
public void execute(MqttRuleContext context) {
try {
// Object[] convertArr = context.getConvertArr();
// // Latitude, longitude
// //主灯档位,激光灯档位,电量百分比,充电状态,电池剩余续航时间
// String mainLightMode = convertArr[1].toString();
// String laserLightMode = convertArr[2].toString();
// String batteryPercentage = convertArr[3].toString();
// String chargeState = convertArr[4].toString();
// String batteryRemainingTime = convertArr[5].toString();
//
// // 发送设备状态和位置信息到Redis
// asyncSendDeviceDataToRedisWithFuture(context.getDeviceImei(), mainLightMode, laserLightMode,
// batteryPercentage, chargeState, batteryRemainingTime);
} catch (Exception e) {
log.error("处理上报数据命令时出错", e);
}
}
/**
* 发送设备状态信息和位置信息到Redis
*
* @param deviceImei 设备IMEI
* @param mainLightMode 主灯档位
* @param laserLightMode 激光灯档位
* @param batteryPercentage 电量百分比
* @param chargeState 充电状态
* @param batteryRemainingTime 电池剩余续航时间
*/
public void asyncSendDeviceDataToRedisWithFuture(String deviceImei, String mainLightMode, String laserLightMode,
String batteryPercentage, String chargeState, String batteryRemainingTime) {
try {
// 构造设备状态信息对象
Map<String, Object> deviceInfo = new LinkedHashMap<>();
deviceInfo.put("deviceImei", deviceImei);
deviceInfo.put("mainLightMode", mainLightMode);
deviceInfo.put("laserLightMode", laserLightMode);
deviceInfo.put("batteryPercentage", batteryPercentage);
deviceInfo.put("chargeState", chargeState);
deviceInfo.put("batteryRemainingTime", batteryRemainingTime);
deviceInfo.put("timestamp", System.currentTimeMillis());
// 将设备状态信息存储到Redis中
String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + deviceImei + DEVICE_STATUS_KEY_PREFIX;
String deviceInfoJson = JsonUtils.toJsonString(deviceInfo);
// 存储到Redis
RedisUtils.setCacheObject(deviceRedisKey, deviceInfoJson);
log.info("设备状态信息已异步发送到Redis: device={}, mainLightMode={}, laserLightMode={}, batteryPercentage={}",
deviceImei, mainLightMode, laserLightMode, batteryPercentage);
} catch (Exception e) {
log.error("异步发送设备信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,135 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.core.utils.date.DurationUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.bo.DeviceAlarmBo;
import com.fuyuanshen.equipment.domain.vo.DeviceAlarmVo;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.service.IDeviceAlarmService;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqAlarmRule implements MqttMessageRule {
private final IDeviceAlarmService deviceAlarmService;
private final DeviceService deviceService;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.ALARM_MESSAGE;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
Object[] convertArr = context.getConvertArr();
String convertValue = convertArr[1].toString();
if (StringUtils.isNotBlank(convertValue)) {
// 将设备状态信息存储到Redis中
String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX;
String sendMessageIng = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + context.getDeviceImei() + ":messageSending";
if ("1".equals(convertValue)) {
RedisUtils.setCacheObject(sendMessageIng, "1", Duration.ofDays(1));
// 存储到Redis
RedisUtils.setCacheObject(deviceRedisKey, "1");
} else if ("0".equals(convertValue)) {
RedisUtils.deleteObject(sendMessageIng);
RedisUtils.deleteObject(deviceRedisKey);
}
}
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
// 保存告警信息
String deviceImei = context.getDeviceImei();
// 设备告警状态 0:解除告警 1:报警产生
Byte state = (Byte) convertArr[1];
savaAlarm(deviceImei, state);
} catch (Exception e) {
log.error("处理告警命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
public void savaAlarm(String deviceImei, Byte state) {
DeviceAlarmVo deviceAlarmVo = deviceAlarmService.queryLatestByDeviceImei(deviceImei);
DeviceAlarmBo deviceAlarmBo = new DeviceAlarmBo();
// 解除告警
if (state == 0) {
if (deviceAlarmVo != null) {
if (deviceAlarmVo.getFinishTime() == null) {
BeanUtil.copyProperties(deviceAlarmVo, deviceAlarmBo);
deviceAlarmBo.setFinishTime(new Date());
String durationBetween = DurationUtils.getDurationBetween(deviceAlarmVo.getStartTime(), deviceAlarmBo.getFinishTime());
deviceAlarmBo.setDurationTime(durationBetween);
// 0已处理1未处理
deviceAlarmBo.setTreatmentState(0);
// 告警状态0 解除告警, 1 告警中
deviceAlarmBo.setAlarmState(0);
deviceAlarmService.updateByBo(deviceAlarmBo);
}
}
}
// 报警产生
if (state == 1) {
if (deviceAlarmVo == null || deviceAlarmVo.getFinishTime() != null) {
Device device = deviceService.selectDeviceByImei(deviceImei);
deviceAlarmBo.setDeviceId(device.getId());
deviceAlarmBo.setDeviceImei(deviceImei);
// 0-强制报警1-撞击闯入2-自动报警3-电子围栏告警
deviceAlarmBo.setDeviceAction(0);
deviceAlarmBo.setStartTime(new Date());
// 0已处理1未处理
deviceAlarmBo.setTreatmentState(1);
// 告警状态0 解除告警, 1 告警中
deviceAlarmBo.setAlarmState(1);
// LoginUser loginUser = LoginHelper.getLoginUser();
// deviceAlarmBo.setCreateBy(loginUser.getUserId());
deviceAlarmBo.setTenantId(device.getTenantId());
String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DEVICE_LOCATION_KEY_PREFIX);
if (StringUtils.isNotBlank(location)) {
JSONObject jsonObject = JSONObject.parseObject(location);
deviceAlarmBo.setLocation(jsonObject.getString("address"));
}
deviceAlarmService.insertByBo(deviceAlarmBo);
}
}
}
}

View File

@ -0,0 +1,84 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_BOOT_LOGO_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 上传开机图片命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqBootLogoRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.BOOT_LOGO;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Byte val2 = (Byte) context.getConvertArr()[1];
// if (val2 == 100) {
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
// return;
// }
//
// String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + context.getDeviceImei() +DEVICE_BOOT_LOGO_KEY_PREFIX);
// if (StringUtils.isEmpty(data)) {
// return;
// }
//
// byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
// byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, (val2 - 1), 512);
// log.info("第{}块数据大小: {} 字节", val2, specificChunk.length);
//
// ArrayList<Integer> intData = new ArrayList<>();
// intData.add(3);
// intData.add((int) val2);
// ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk), intData);
// intData.add(0);
// intData.add(0);
// intData.add(0);
// intData.add(0);
//
// Map<String, Object> map = new HashMap<>();
// map.put("instruct", intData);
//
// mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(), 1, JsonUtils.toJsonString(map));
// log.info("发送开机LOGO点阵数据到设备消息=>topic:{},payload:{}",
// MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(),
// JsonUtils.toJsonString(map));
} catch (Exception e) {
log.error("处理开机LOGO时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
}

View File

@ -0,0 +1,74 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqLaserModeSettingsRule implements MqttMessageRule {
@Override
public String getCommandType() {
return LightingCommandTypeConstants.LASER_LIGHT;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Object[] convertArr = context.getConvertArr();
//
// String mode = convertArr[1].toString();
// if(StringUtils.isNotBlank(mode)){
// // 发送设备状态和位置信息到Redis
// syncSendDeviceDataToRedisWithFuture(context.getDeviceImei(),mode);
// }
//
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(30));
} catch (Exception e) {
log.error("处理激光模式命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(30));
}
}
/**
* 发送设备状态信息和位置信息到Redis
*
* @param deviceImei 设备IMEI
*/
public void syncSendDeviceDataToRedisWithFuture(String deviceImei,Object convertValue) {
// CompletableFuture.runAsync(() -> {
//
// });
try {
// 将设备状态信息存储到Redis中
String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + deviceImei + DEVICE_LASER_MODE_KEY_PREFIX;
// 存储到Redis
RedisUtils.setCacheObject(deviceRedisKey, convertValue.toString());
} catch (Exception e) {
log.error("异步发送设备信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
}

View File

@ -0,0 +1,51 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqLightBrightnessRule implements MqttMessageRule {
@Override
public String getCommandType() {
return LightingCommandTypeConstants.MAIN_LIGHT_BRIGHTNESS;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Object[] convertArr = context.getConvertArr();
//
// String convertValue = convertArr[1].toString();
// // 将设备状态信息存储到Redis中
// String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX;
//
// // 存储到Redis
// RedisUtils.setCacheObject(deviceRedisKey, convertValue);
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
} catch (Exception e) {
log.error("处理灯光亮度命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
}

View File

@ -0,0 +1,246 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.utils.map.GetAddressFromLatUtil;
import com.fuyuanshen.equipment.utils.map.LngLonUtil;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_LOCATION_KEY_PREFIX;
/**
* 定位数据命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqLocationDataRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
private final DeviceService deviceService;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.LOCATION_DATA;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Object[] convertArr = context.getConvertArr();
// // Latitude, longitude
// String latitude = convertArr[1].toString();
// String longitude = convertArr[2].toString();
// // 判断 latitude 和 longitude 是否都为 0
// if ("0".equals(latitude) && "0".equals(longitude)) {
// log.info("位置信息为0不存储到Redis: device={}, lat={}, lon={}", context.getDeviceImei(), latitude, longitude);
// return;
// }
// // 异步发送经纬度到Redis
// asyncSendLocationToRedisWithFuture(context.getDeviceImei(), latitude, longitude);
// // 异步保存数据
// asyncSaveLocationToMySQLWithFuture(context.getDeviceImei(), latitude, longitude);
//
// Map<String, Object> map = buildLocationDataMap(latitude, longitude);
// mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(), 1, JsonUtils.toJsonString(map));
// log.info("发送定位数据到设备=>topic:{},payload:{}",
// MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(),
// JsonUtils.toJsonString(map));
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
} catch (Exception e) {
log.error("处理定位数据命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
/**
* 异步发送位置信息到Redis
*
* @param deviceImei 设备IMEI
* @param latitude 纬度
* @param longitude 经度
* @param timestamp 时间戳
*/
// @Async
// public void asyncSendLocationToRedis(String deviceImei, String latitude, String longitude, long timestamp) {
// try {
// // 构造位置信息对象
// Map<String, Object> locationInfo = new HashMap<>();
// locationInfo.put("deviceImei", deviceImei);
// locationInfo.put("latitude", latitude);
// locationInfo.put("longitude", longitude);
// locationInfo.put("timestamp", timestamp);
//
// // 将位置信息存储到Redis中使用设备IMEI作为key的一部分
// String redisKey = "device:location:" + deviceImei;
// String locationJson = JsonUtils.toJsonString(locationInfo);
//
// // 存储到Redis设置过期时间例如24小时
// RedisUtils.setCacheObject(redisKey, locationJson, Duration.ofSeconds(24 * 60 * 60));
//
// // 也可以存储到一个列表中,保留历史位置信息
// String locationHistoryKey = "device:location:history:" + deviceImei;
// RedisUtils.lPush(locationHistoryKey, locationJson, 24 * 60 * 60);
//
// log.info("位置信息已异步发送到Redis: device={}, lat={}, lon={}", deviceImei, latitude, longitude);
// } catch (Exception e) {
// log.error("异步发送位置信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
// }
// }
/**
* 异步发送位置信息到Redis使用CompletableFuture
*
* @param deviceImei 设备IMEI
* @param latitude 纬度
* @param longitude 经度
*/
public void asyncSendLocationToRedisWithFuture(String deviceImei, String latitude, String longitude) {
try {
if (StringUtils.isBlank(latitude) || StringUtils.isBlank(longitude)) {
return;
}
// String[] latArr = latitude.split("\\.");
// String[] lonArr = longitude.split("\\.");
// // 将位置信息存储到Redis中
String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DEVICE_LOCATION_KEY_PREFIX;
// String redisObj = RedisUtils.getCacheObject(redisKey);
// JSONObject jsonOBj = JSONObject.parseObject(redisObj);
// if(jsonOBj != null){
// String str1 = latArr[0] +"."+ latArr[1].substring(0,4);
// String str2 = lonArr[0] +"."+ lonArr[1].substring(0,4);
//
// String cacheLatitude = jsonOBj.getString("wgs84_latitude");
// String cacheLongitude = jsonOBj.getString("wgs84_longitude");
// String[] latArr1 = cacheLatitude.split("\\.");
// String[] lonArr1 = cacheLongitude.split("\\.");
//
// String cacheStr1 = latArr1[0] +"."+ latArr1[1].substring(0,4);
// String cacheStr2 = lonArr1[0] +"."+ lonArr1[1].substring(0,4);
// if(str1.equals(cacheStr1) && str2.equals(cacheStr2)){
// log.info("位置信息未发生变化: device={}, lat={}, lon={}", deviceImei, latitude, longitude);
// return;
// }
// }
// 构造位置信息对象
Map<String, Object> locationInfo = new LinkedHashMap<>();
double[] doubles = LngLonUtil.gps84_To_Gcj02(Double.parseDouble(latitude), Double.parseDouble(longitude));
locationInfo.put("deviceImei", deviceImei);
locationInfo.put("latitude", doubles[0]);
locationInfo.put("longitude", doubles[1]);
locationInfo.put("wgs84_latitude", latitude);
locationInfo.put("wgs84_longitude", longitude);
String address = GetAddressFromLatUtil.getAdd(String.valueOf(doubles[1]), String.valueOf(doubles[0]));
locationInfo.put("address", address);
locationInfo.put("timestamp", System.currentTimeMillis());
String locationJson = JsonUtils.toJsonString(locationInfo);
// 存储到Redis
RedisUtils.setCacheObject(redisKey, locationJson);
// 存储到一个列表中,保留历史位置信息
// String locationHistoryKey = GlobalConstants.GLOBAL_REDIS_KEY+DeviceRedisKeyConstants.DEVICE_LOCATION_HISTORY_KEY_PREFIX + deviceImei;
// RedisUtils.addCacheList(locationHistoryKey, locationJson);
// RedisUtils.expire(locationHistoryKey, Duration.ofDays(90));
storeDeviceTrajectoryWithSortedSet(deviceImei, locationJson);
log.info("位置信息已异步发送到Redis: device={}, lat={}, lon={}", deviceImei, latitude, longitude);
} catch (Exception e) {
log.error("异步发送位置信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
/**
* 异步保存位置信息到MySQL数据库
*
* @param deviceImei 设备IMEI
* @param latitude 纬度
* @param longitude 经度
*/
public void asyncSaveLocationToMySQLWithFuture(String deviceImei, String latitude, String longitude) {
try {
if (StringUtils.isBlank(latitude) || StringUtils.isBlank(longitude)) {
return;
}
// 调用服务层方法更新设备位置信息
deviceService.updateDeviceLocationByImei(deviceImei, longitude, latitude);
log.info("位置信息已异步保存到MySQL: device={}, lat={}, lon={}", deviceImei, latitude, longitude);
} catch (Exception e) {
log.error("异步保存位置信息到MySQL时出错: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
/**
* 存储设备30天历史轨迹到Redis (使用Sorted Set)
*/
public void storeDeviceTrajectoryWithSortedSet(String deviceImei, String locationJson) {
try {
String trajectoryKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DeviceRedisKeyConstants.DEVICE_LOCATION_HISTORY_KEY_PREFIX;
// String trajectoryKey = "device:trajectory:zset:" + deviceImei;
// String locationJson = JsonUtils.toJsonString(locationInfo);
long timestamp = System.currentTimeMillis();
// 添加到Sorted Set使用时间戳作为score
RedisUtils.zAdd(trajectoryKey, locationJson, timestamp);
// // 设置30天过期时间
// RedisUtils.expire(trajectoryKey, Duration.ofDays(30));
// 清理30天前的数据冗余保护
long thirtyDaysAgo = System.currentTimeMillis() - (7L * 24 * 60 * 60 * 1000);
RedisUtils.zRemoveRangeByScore(trajectoryKey, 0, thirtyDaysAgo);
} catch (Exception e) {
log.error("存储设备轨迹到Redis(ZSet)失败: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
private Map<String, Object> buildLocationDataMap(String latitude, String longitude) {
String[] latArr = latitude.split("\\.");
String[] lonArr = longitude.split("\\.");
ArrayList<Integer> intData = new ArrayList<>();
intData.add(11);
intData.add(Integer.parseInt(latArr[0]));
String str1 = latArr[1];
intData.add(Integer.parseInt(str1.substring(0, 4)));
String str2 = lonArr[1];
intData.add(Integer.parseInt(lonArr[0]));
intData.add(Integer.parseInt(str2.substring(0, 4)));
Map<String, Object> map = new HashMap<>();
map.put("instruct", intData);
return map;
}
}

View File

@ -0,0 +1,147 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.core.utils.date.DurationUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.bo.DeviceAlarmBo;
import com.fuyuanshen.equipment.domain.vo.DeviceAlarmVo;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.service.IDeviceAlarmService;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqModeRule implements MqttMessageRule {
private final DeviceService deviceService;
private final IDeviceAlarmService deviceAlarmService;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.LIGHT_MODE;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
log.info("处理灯光模式命令");
log.info("MQTT消息负载字典{}", context.getPayloadDict());
// Object[] convertArr = context.getConvertArr();
//
// String mainLightMode = convertArr[1].toString();
// String batteryRemainingTime = convertArr[2].toString();
// if (StringUtils.isNotBlank(mainLightMode)) {
// log.info("设备离线mainLightMode{}", mainLightMode);
// if ("0".equals(mainLightMode)) {
//
// // 设备离线
// String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + context.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
// RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "0");
//
// String sendMessageIng = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + context.getDeviceImei() + ":messageSending";
// String messageSendingValue = RedisUtils.getCacheObject(sendMessageIng);
// if ("1".equals(messageSendingValue)) {
// // 设置为故障状态
// RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "2");
// UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
// updateWrapper.eq("device_imei", context.getDeviceImei());
// updateWrapper.set("online_status", 2);
// deviceService.update(updateWrapper);
// RedisUtils.deleteObject(sendMessageIng);
//
// // 解除告警
// String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX;
// if (RedisUtils.getCacheObject(deviceRedisKey) != null) {
// RedisUtils.deleteObject(deviceRedisKey);
// }
// cancelAlarm(context.getDeviceImei());
// }
// }
// // 发送设备状态和位置信息到Redis
// syncSendDeviceDataToRedisWithFuture(context.getDeviceImei(), mainLightMode);
// String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX;
//
// // 存储到Redis
// RedisUtils.setCacheObject(deviceRedisKey, batteryRemainingTime);
// }
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
} catch (Exception e) {
log.error("处理灯光模式命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
/**
* 发送设备状态信息和位置信息到Redis
*
* @param deviceImei 设备IMEI
*/
public void syncSendDeviceDataToRedisWithFuture(String deviceImei, Object convertValue) {
// CompletableFuture.runAsync(() -> {
//
// });
try {
// 将设备状态信息存储到Redis中
String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + deviceImei + DEVICE_LIGHT_MODE_KEY_PREFIX;
// 存储到Redis
RedisUtils.setCacheObject(deviceRedisKey, convertValue.toString());
} catch (Exception e) {
log.error("异步发送设备信息到Redis时出错: device={}, error={}", deviceImei, e.getMessage(), e);
}
}
/**
* 解除告警
*
* @param deviceImei 设备IMEI
*/
public void cancelAlarm(String deviceImei) {
DeviceAlarmVo deviceAlarmVo = deviceAlarmService.queryLatestByDeviceImei(deviceImei);
DeviceAlarmBo deviceAlarmBo = new DeviceAlarmBo();
if (deviceAlarmVo != null) {
if (deviceAlarmVo.getFinishTime() == null) {
BeanUtil.copyProperties(deviceAlarmVo, deviceAlarmBo);
deviceAlarmBo.setFinishTime(new Date());
String durationBetween = DurationUtils.getDurationBetween(deviceAlarmVo.getStartTime(), deviceAlarmBo.getFinishTime());
deviceAlarmBo.setDurationTime(durationBetween);
// 0已处理1未处理
deviceAlarmBo.setTreatmentState(0);
// 告警状态0 解除告警, 1 告警中
deviceAlarmBo.setAlarmState(0);
deviceAlarmService.updateByBo(deviceAlarmBo);
}
}
}
}

View File

@ -0,0 +1,45 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
/**
* 定位数据命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqPersonnelInfoDataRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.PERSONNEL_INFO;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Object[] convertArr = context.getConvertArr();
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(30));
} catch (Exception e) {
log.error("处理定位数据命令时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(30));
}
}
}

View File

@ -0,0 +1,95 @@
package com.fuyuanshen.global.mqtt.rule.bjq;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 人员信息命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqSendMessageRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.SEND_MESSAGE;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
// Byte val2 = (Byte) context.getConvertArr()[1];
// String val2Str = context.getConvertArr()[1].toString();
// int val2 = Integer.parseInt(val2Str);
// System.out.println("收到设备信息命令:"+val2);
// if (val2 == 100) {
// RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
// return;
// }
//
// if(val2==200){
// String sendMessageIng = GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + context.getDeviceImei() + ":messageSending";
// RedisUtils.deleteObject(sendMessageIng);
// return;
// }
//
//
// String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + context.getDeviceImei() + ":app_send_message_data");
// if (StringUtils.isEmpty(data)) {
// return;
// }
//
// byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
// byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, (val2 - 1), 512);
// log.info("第{}块数据大小: {} 字节", val2, specificChunk.length);
//// System.out.println("第" + val2 + "块数据: " + Arrays.toString(specificChunk));
//
// ArrayList<Integer> intData = new ArrayList<>();
// intData.add(6);
// intData.add(val2);
// ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk), intData);
// intData.add(0);
// intData.add(0);
// intData.add(0);
// intData.add(0);
//
// Map<String, Object> map = new HashMap<>();
// map.put("instruct", intData);
//
// mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(), 1, JsonUtils.toJsonString(map));
// log.info("发送设备信息数据到设备消息=>topic:{},payload:{}",
// MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(),
// JsonUtils.toJsonString(map));
} catch (Exception e) {
log.error("处理发送设备信息时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 爆闪模式开启/关闭
*/
@Slf4j
@Component
public class FuncType10StrobeMode implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_10";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J爆闪模式开启/关闭,消息负载:{}", context.getPayloadDict());
try {
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":strobeMode";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J爆闪模式开启/关闭失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 修改警示灯爆闪频率
*/
@Slf4j
@Component
public class FuncType11Frequency implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_11";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J修改警示灯爆闪频率消息负载{}", context.getPayloadDict());
try {
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":frequency";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J修改警示灯爆闪频率失败", e);
}
}
}

View File

@ -0,0 +1,45 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 强制声光报警开启/关闭
*/
@Slf4j
@Component
public class FuncType12ForceAudio implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_12";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J强制声光报警开启/关闭,消息负载:{}", context.getPayloadDict());
try {
// 构建强制声光报警开关的Redis键
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":forceAudio";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// // 存储强制声光报警开关状态到Redis
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J强制声光报警开启/关闭失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 警示灯LED亮度调节
*/
@Slf4j
@Component
public class FuncType13Brightness implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_13";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J警示灯LED亮度调节消息负载{}", context.getPayloadDict());
try {
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":brightness";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J警示灯LED亮度调节失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 获取警示灯的当前工作方式(设备下发返回响应数据、设备定时主动上报)
*/
@Slf4j
@Component
public class FuncType14Report implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_14";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J设备定时主动上报消息负载{}", context.getPayloadDict());
try {
String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
context.getDeviceImei() + ":report";
Map<String, Object> payloadDict = context.getPayloadDict();
if (payloadDict != null) {
RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
}
} catch (Exception e) {
log.error("HBY100J设备定时主动上报失败", e);
}
}
}

View File

@ -0,0 +1,46 @@
//package com.fuyuanshen.global.mqtt.rule.hby100j;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.fuyuanshen.common.core.constant.GlobalConstants;
//import com.fuyuanshen.common.redis.utils.RedisUtils;
//import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
//import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.util.Map;
//
//import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
//
///**
// * 设备复位
// */
//@Slf4j
//@Component
//public class FuncType1Rest implements NewMqttMessageRule {
//
// @Override
// public String getCommandType() {
// return "HBY100_1";
// }
//
// @Override
// public void execute(NewMqttRuleContext context) {
// log.info("开始处理设备复位,消息负载:{}", context.getPayloadDict());
//
// try {
// // 构建强制声光报警开关的Redis键
//// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
//// context.getDeviceImei() + ":force_audio_visual_alarm_switch";
////
//// Map<String, Object> payloadDict = context.getPayloadDict();
//// if (payloadDict != null) {
//// // 存储强制声光报警开关状态到Redis
//// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
//// }
// log.info("设备复位设备ID{}", context.getDeviceImei());
// } catch (Exception e) {
// log.error("处理设备复位失败", e);
// }
// }
//}

View File

@ -0,0 +1,46 @@
//package com.fuyuanshen.global.mqtt.rule.hby100j;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.fuyuanshen.common.core.constant.GlobalConstants;
//import com.fuyuanshen.common.redis.utils.RedisUtils;
//import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
//import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//
//import java.util.Map;
//
//import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
//
///**
// * 获取设备基础信息
// */
//@Slf4j
//@Component
//public class FuncType2BaseInfo implements NewMqttMessageRule {
//
// @Override
// public String getCommandType() {
// return "HBY100_2";
// }
//
// @Override
// public void execute(NewMqttRuleContext context) {
// log.info("开始处理强制声光报警开关,消息负载:{}", context.getPayloadDict());
//
// try {
// // 构建强制声光报警开关的Redis键
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":force_audio_visual_alarm_switch";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// // 存储强制声光报警开关状态到Redis
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
// log.info("强制声光报警开关处理完成设备ID{}", context.getDeviceImei());
// } catch (Exception e) {
// log.error("处理强制声光报警开关失败", e);
// }
// }
//}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 获取设备位置信息(设备下发返回响应数据、设备定时主动上报)
*/
@Slf4j
@Component
public class FuncType3Location implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_3";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J获取设备位置信息消息负载{}", context.getPayloadDict());
try {
String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
context.getDeviceImei() + ":location";
Map<String, Object> payloadDict = context.getPayloadDict();
if (payloadDict != null) {
RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
}
} catch (Exception e) {
log.error("HBY100J获取设备位置信息失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 获取设备电源状态(设备下发返回响应数据、设备定时主动上报)
*/
@Slf4j
@Component
public class FuncType4PowerStatus implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_4";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J获取设备电源状态消息负载{}", context.getPayloadDict());
try {
String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
context.getDeviceImei() + ":powerStatus";
Map<String, Object> payloadDict = context.getPayloadDict();
if (payloadDict != null) {
RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
}
} catch (Exception e) {
log.error("HBY100J获取设备电源状态失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 更新语音
*/
@Slf4j
@Component
public class FuncType5UpdateVoice implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_5";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J更新语音消息负载{}", context.getPayloadDict());
try {
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":updateVoice";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J更新语音失败", e);
}
}
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.global.mqtt.rule.hby100j;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.NewMqttMessageRule;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Map;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 语音播报开启/关闭
*/
@Slf4j
@Component
public class FuncType6VoicePlay implements NewMqttMessageRule {
@Override
public String getCommandType() {
return "HBY100_9";
}
@Override
public void execute(NewMqttRuleContext context) {
log.info("HBY100J语音播报开启/关闭,消息负载:{}", context.getPayloadDict());
try {
// String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
// context.getDeviceImei() + ":VoicePlay";
//
// Map<String, Object> payloadDict = context.getPayloadDict();
// if (payloadDict != null) {
// RedisUtils.setCacheObject(redisKey, JSONObject.toJSONString(payloadDict));
// }
} catch (Exception e) {
log.error("HBY100J语音播报开启/关闭失败", e);
}
}
}

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