0
0

178 Commits

Author SHA1 Message Date
c34a39a308 WebApp用户信息 2025-08-21 15:11:22 +08:00
b08d23eef4 Merge branch 'main' into fys-prod
# Conflicts:
#	fys-admin/src/main/resources/application-prod.yml
2025-08-21 09:59:23 +08:00
add0738b28 Merge remote-tracking branch 'origin/main' 2025-08-21 09:55:26 +08:00
b61c9c7a06 配置文件提交 2025-08-21 09:54:42 +08:00
8106d09e67 生产配置 2025-08-20 16:53:27 +08:00
425ea306e3 Merge branch 'main' into fys-prod 2025-08-20 16:48:48 +08:00
fd7768acc9 Merge remote-tracking branch 'upstream/6170' 2025-08-20 16:45:49 +08:00
bb11bc4dfa WEB端解绑设备 2025-08-20 15:13:43 +08:00
7f65ebedc2 数据字典信息 2025-08-20 13:31:54 +08:00
75756eb8ab Merge remote-tracking branch 'upstream/6170'
# Conflicts:
#	fys-common/fys-common-encrypt/src/main/java/com/fuyuanshen/common/encrypt/utils/EncryptUtilsTest.java
2025-08-19 14:11:02 +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
285abaedfb Merge branch 'main' into fys-prod 2025-08-15 14:37:23 +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
07bc831f1a 登录测试 2025-08-13 19:21:57 +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
65caea4a00 解决冲突 2025-08-07 18:17:49 +08:00
83458d0060 Merge remote-tracking branch 'upstream/main'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/service/AppDeviceBizService.java
#	fys-admin/src/main/java/com/fuyuanshen/app/service/AppLoginService.java
#	fys-admin/src/main/java/com/fuyuanshen/web/handler/mqtt/DeviceReceiverMessageHandler.java
#	fys-admin/src/main/resources/application-prod.yml
#	fys-modules/fys-app/src/main/java/com/fuyuanshen/app/service/impl/AppUserServiceImpl.java
2025-08-07 18:10:47 +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
0b0cc84eea Merge branch 'main' into fys-prod 2025-08-04 09:39:08 +08:00
ae393e8155 校验设备类型名称 2025-08-04 09:36:17 +08:00
38caba1fad 修改用户状态-强制下线 2025-08-04 09:35:59 +08:00
6626a1a35e 设备行为 2025-08-04 09:34:16 +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
4271085e78 用户注销 2025-08-01 09:58:33 +08:00
2cb4f5b83e 设备绑定优化2 2025-08-01 09:07:27 +08:00
a3a1d43dde Merge remote-tracking branch 'origin/main'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/app/service/AppDeviceBizService.java
#	fys-modules/fys-app/src/main/java/com/fuyuanshen/app/domain/AppDeviceBindRecord.java
2025-08-01 09:06:03 +08:00
5f4b12a320 设备绑定优化 2025-08-01 09:00:32 +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
f2c7549d6e Merge branch 'main' into fys-prod 2025-07-31 09:24:23 +08:00
7bd652f9b8 Merge remote-tracking branch 'upstream/main' 2025-07-31 09:23:34 +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
9ffdcace53 LngLonUtil.java 2025-07-28 10:41:09 +08:00
8cc969bbe6 Merge remote-tracking branch 'upstream/main' 2025-07-28 10:40:31 +08:00
6a900335ef LngLonUtil.java 2025-07-28 10:40:13 +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
f1806fa482 app用户登录 2025-07-24 14:49:40 +08:00
17ed75f54a Merge branch 'main' into fys-prod 2025-07-23 19:26:46 +08:00
0abc5d48c0 Merge remote-tracking branch 'upstream/main' 2025-07-23 19:26:12 +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
e7c8e245ba Merge remote-tracking branch 'upstream/main' 2025-07-23 11:01:01 +08:00
80b944cbf0 Merge remote-tracking branch 'upstream/main' into fys-prod
# Conflicts:
#	fys-admin/pom.xml
2025-07-23 10:57:03 +08:00
da6b888934 Merge branch 'dyf-device' 2025-07-23 10:54:20 +08:00
619356209b 删除设备 2025-07-23 10:53:26 +08:00
d84a7cde3b 帐号状态(0正常 1停用)status 2025-07-23 09:52:28 +08:00
e4dbee15dd 设备分享功能开发 2025-07-22 18:37:02 +08:00
33e53de5a1 设备主题 2025-07-22 16:13:39 +08:00
3bce279d7b 修改客户-用户名重复校验 2025-07-22 09:58:49 +08:00
9338b0d24b 设备详情功能开发 2025-07-21 15:24:26 +08:00
537cc0b2d7 Merge branch 'main' into fys-prod
# Conflicts:
#	pom.xml
2025-07-21 08:45:53 +08:00
8750bc8e10 Merge remote-tracking branch 'upstream/main' 2025-07-21 08:43:34 +08:00
6dde6c3a3b 去掉demo 2025-07-21 08:42:21 +08:00
879e485056 Merge branch 'dyf-device' 2025-07-21 08:39:55 +08:00
bb096f53cd 去除demo模块 2025-07-19 16:16:22 +08:00
38724dbfad Merge branch 'main' into fys-prod 2025-07-19 15:58:51 +08:00
69c4cc2004 APP设备分享功能开发2 2025-07-19 14:28:07 +08:00
e9227dea89 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	fys-admin/src/main/java/com/fuyuanshen/web/controller/CaptchaController.java
2025-07-19 14:24:21 +08:00
b369b28949 新增忘记密码手机短信验证码 2025-07-19 14:23:29 +08:00
a7340c744e APP客户设备绑定-绑定时间 2025-07-19 14:22:36 +08:00
f1d1528c40 Merge remote-tracking branch 'upstream/main'
# Conflicts:
#	fys-common/fys-common-core/src/main/java/com/fuyuanshen/common/core/constant/GlobalConstants.java
2025-07-19 10:26:52 +08:00
6bbe9cbdd1 Merge branch 'dyf-device' 2025-07-19 10:21:11 +08:00
3feafc2cd9 删除设备类型 2025-07-19 10:20:07 +08:00
13986bb493 APP设备分享功能开发 2025-07-19 09:36:35 +08:00
f2921ff12f 分页查询设备-设备类型 2025-07-19 09:17:14 +08:00
ec89dd8c1e 新增设备 校验 2025-07-18 18:12:36 +08:00
57322c9c87 蓝牙名称 2025-07-18 17:57:58 +08:00
73e1df4232 Merge branch 'main' into fys-prod 2025-07-18 16:30:02 +08:00
fys
4e608b8f3a merge upstream 2025-07-18 16:24:05 +08:00
7d91426414 Merge branch 'dyf-device' 2025-07-18 15:17:18 +08:00
ad06811747 撤回设备 2025-07-18 15:06:39 +08:00
dyf
aeaa906bc9 Merge pull request 'feat(fys-demo): 添加视频上传和处理功能' (#5) from liwenlong/fys-Multi-tenant:jingquan into main
Reviewed-on: dyf/fys-Multi-tenant#5
2025-07-18 14:03:18 +08:00
36092932bf feat(fys-demo): 添加视频上传和处理功能
- 新增 VideoUploadController 控制器处理视频上传
- 添加视频帧提取和转换为 RGB565 格式功能
- 实现视频文件大小和格式校验
- 优化临时文件创建和清理逻辑
- 引入 javacv-platform依赖进行视频处理
2025-07-18 13:27:26 +08:00
34188f20dd 帐号状态(0正常 1停用) 2025-07-18 11:18:30 +08:00
0fa0e4ab1b 帐号状态(0正常 1停用) 2025-07-18 10:36:02 +08:00
e321dcd652 修改客户状态 2025-07-18 10:23:04 +08:00
e35955f156 prod 2025-07-17 17:27:14 +08:00
3c2d97aaf2 提交 2025-07-17 17:17:30 +08:00
6ed1241a6d Merge remote-tracking branch 'upstream/main'
# Conflicts:
#	fys-modules/fys-app/src/main/resources/mapper/app/AppBusinessFileMapper.xml
2025-07-17 17:03:25 +08:00
78e2538f71 Merge branch 'dyf-device' 2025-07-17 16:41:08 +08:00
faef79e56d return R.ok(); 2025-07-17 16:29:25 +08:00
7b1615ce4d WEB端解绑设备 2025-07-17 16:20:22 +08:00
171eeabea1 Merge branch 'dyf-device' 2025-07-17 09:24:10 +08:00
cc776300ec 删除设备 逻辑修改 2025-07-17 09:23:11 +08:00
04df7e3ec7 可靠点阵生成工具 - 终极版 2025-07-16 08:46:21 +08:00
7be94fe1d2 产品参数bug修改 2025-07-15 15:59:32 +08:00
6f24759361 发送指令显示工具 2025-07-15 15:58:12 +08:00
1cf7c47ef9 正式环境配置提交 2025-07-14 16:28:54 +08:00
530ee83488 新增绑定时间字段 2025-07-14 14:23:17 +08:00
f938716e2d 分页查询APP用户信息列表 2025-07-14 10:03:51 +08:00
bbf1c6cfd5 分页查询设备:设备类型自动更新 2025-07-14 09:13:30 +08:00
082f890009 登录查询用户新增用户类型查询条件 2025-07-14 09:02:13 +08:00
800b825892 登录查询用户新增用户类型查询条件 2025-07-14 08:53:53 +08:00
bdee8c8383 Merge remote-tracking branch 'origin/main' 2025-07-12 15:31:42 +08:00
6f4e18fb3f 文件管理代码优化 2025-07-12 15:31:27 +08:00
fys
3ca6b69709 merge upstream 2025-07-12 14:04:03 +08:00
cfafbc54f7 Merge branch 'dyf-device' 2025-07-12 14:01:00 +08:00
fdb64b1dcc 小程序:相关接口 2025-07-12 13:57:31 +08:00
e13e3c57a6 解绑问题修改2 2025-07-12 10:41:35 +08:00
fbbe90207e 解绑问题修复 2025-07-12 10:41:13 +08:00
56704f6014 个人中心修改 2025-07-12 10:18:12 +08:00
2f38f08538 Merge remote-tracking branch 'origin/main' 2025-07-12 09:56:42 +08:00
eb1552d982 绑定蓝牙问题修复 2025-07-12 09:56:26 +08:00
4f00c69f91 绑定优化2 2025-07-12 09:55:29 +08:00
fcd17634dc 绑定优化 2025-07-12 09:54:08 +08:00
24f0caacd5 绑定蓝牙问题解决 2025-07-12 09:52:14 +08:00
c73a700210 app登录配置修改 2025-07-11 17:39:53 +08:00
3ed2f97752 app接口功能实现 2025-07-11 16:40:20 +08:00
dyf
1eb2502a21 revert 2815e27240
revert 晶全代码同步,app接口开发
2025-07-11 16:20:24 +08:00
2815e27240 晶全代码同步,app接口开发 2025-07-11 16:03:36 +08:00
f119dd158b 操作视频信息 2025-07-11 14:06:25 +08:00
a109f187b9 Merge branch 'main' into jingquan 2025-07-11 11:37:59 +08:00
b5ebc8855d Merge branch 'main' into jingquan 2025-07-11 11:36:41 +08:00
99aef4b353 Merge branch 'main' into dyf-device 2025-07-11 11:36:17 +08:00
a423ac0f8b app设备解绑 2025-07-11 11:34:30 +08:00
211 changed files with 13014 additions and 809 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

@ -94,10 +94,10 @@
</dependency>
<!-- demo模块 -->
<dependency>
<groupId>com.fuyuanshen</groupId>
<artifactId>fys-demo</artifactId>
</dependency>
<!-- <dependency> -->
<!-- <groupId>com.fuyuanshen</groupId> -->
<!-- <artifactId>fys-demo</artifactId> -->
<!-- </dependency> -->
<!-- 工作流模块 -->
<dependency>

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

@ -4,14 +4,13 @@ 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 com.fuyuanshen.app.model.AppSmsLoginBody;
import com.fuyuanshen.app.service.AppLoginService;
import com.fuyuanshen.common.core.constant.SystemConstants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.domain.model.SmsLoginBody;
import com.fuyuanshen.common.core.domain.model.AppLoginBody;
import com.fuyuanshen.common.core.domain.model.AppSmsRegisterBody;
import com.fuyuanshen.common.core.domain.model.PasswordLoginBody;
import com.fuyuanshen.common.core.utils.*;
import com.fuyuanshen.common.encrypt.annotation.ApiEncrypt;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
@ -24,8 +23,8 @@ import com.fuyuanshen.system.service.ISysTenantService;
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.AppRegisterService;
import com.fuyuanshen.web.service.IAuthStrategy;
import com.fuyuanshen.web.service.SysRegisterService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -51,7 +50,7 @@ import java.util.List;
public class AppAuthController {
private final AppLoginService loginService;
private final SysRegisterService registerService;
private final AppRegisterService registerService;
private final ISysConfigService configService;
private final ISysTenantService tenantService;
private final ISysClientService clientService;
@ -64,15 +63,15 @@ public class AppAuthController {
*/
// @ApiEncrypt
@PostMapping("/login")
public R<LoginVo> login(@RequestBody AppSmsLoginBody appSmsLoginBody) {
public R<LoginVo> login(@RequestBody AppLoginBody appLoginBody) {
// 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");
ValidatorUtils.validate(appLoginBody);
PasswordLoginBody loginBody = new PasswordLoginBody();
loginBody.setUsername(appLoginBody.getUserName());
loginBody.setPassword(appLoginBody.getPassword());
loginBody.setTenantId(appLoginBody.getTenantId());
loginBody.setClientId("835b15335d389c9fcfdf99421fa8019b");
loginBody.setGrantType("appPassword");
// 授权类型和客户端id
String clientId = loginBody.getClientId();
String grantType = loginBody.getGrantType();
@ -93,26 +92,29 @@ public class AppAuthController {
}
/**
* 用户注销
*/
@DeleteMapping("/cancelAccount")
public R<Void> cancelAccount() {
loginService.cancelAccount();
return R.ok("用户注销成功");
}
/**
* 退出登录
*/
@PostMapping("/logout")
public R<Void> logout() {
// loginService.logout();
loginService.logout();
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 AppSmsRegisterBody user) {
registerService.register(user);
return R.ok();
}

View File

@ -1,24 +1,26 @@
package com.fuyuanshen.app.controller;
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.service.equipment.APPDeviceService;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
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.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.service.DeviceService;
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 设备信息管理
* APP设备信息管理
*/
@Validated
@RequiredArgsConstructor
@ -26,18 +28,15 @@ import java.util.List;
@RequestMapping("/app/device")
public class AppDeviceController extends BaseController {
private final DeviceService deviceService;
private final DeviceBizService appDeviceService;
private final APPDeviceService appDeviceService;
/**
* 查询设备列表
*/
@GetMapping("/list")
public TableDataInfo<AppDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return deviceService.queryAppDeviceList(bo,pageQuery);
return appDeviceService.queryAppDeviceList(bo,pageQuery);
}
/**
@ -45,7 +44,7 @@ public class AppDeviceController extends BaseController {
*/
@PostMapping("/bind")
public R<Void> bind(@RequestBody AppDeviceBo bo) {
return toAjax(deviceService.bindDevice(bo));
return toAjax(appDeviceService.bindDevice(bo));
}
@ -54,7 +53,7 @@ public class AppDeviceController extends BaseController {
*/
@DeleteMapping("/unBind")
public R<Void> unBind(Long id) {
return toAjax(deviceService.unBindDevice(id));
return toAjax(appDeviceService.unBindDevice(id));
}
/**
@ -76,4 +75,19 @@ public class AppDeviceController extends BaseController {
appDeviceService.reName(reNameDTO);
return R.ok("重命名成功!!!");
}
@GetMapping("/realTimeStatus")
public R<Map<String, Object>> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
Map<String, Object> status = appDeviceService.getRealTimeStatus(statusDto);
return R.ok(status);
}
/**
* 根据mac查询设备信息
*/
@GetMapping("/getDeviceInfoByDeviceMac")
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
}
}

View File

@ -0,0 +1,118 @@
package com.fuyuanshen.app.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareDetailVo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.service.IAppDeviceShareService;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.idempotent.annotation.RepeatSubmit;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
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;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
import java.util.LinkedHashMap;
import static com.fuyuanshen.common.core.constant.GlobalConstants.DEVICE_SHARE_CODES_KEY;
/**
* APP 设备分享
*
* @author Lion Li
* @date 2025-07-16
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/deviceShare")
public class AppDeviceShareController extends BaseController {
private final IAppDeviceShareService deviceShareService;
private final DeviceShareService appDeviceShareService;
/**
* 分享管理列表
*/
@GetMapping("/deviceShareList")
public TableDataInfo<AppDeviceShareVo> list(AppDeviceShareBo bo, PageQuery pageQuery) {
return appDeviceShareService.queryPageList(bo, pageQuery);
}
/**
* 他人分享管理列表
*/
@GetMapping("/otherDeviceShareList")
public TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery) {
return appDeviceShareService.otherDeviceShareList(bo, pageQuery);
}
/**
* 获取设备分享详细信息
*
* @param id 主键
*/
@GetMapping("/{id}")
public R<AppDeviceShareDetailVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceShareService.getInfo(id));
}
/**
* 新增设备分享
*/
@RepeatSubmit()
@PostMapping("/deviceShare")
public R<Void> deviceShare(@Validated(AddGroup.class) @RequestBody AppDeviceShareBo bo) {
return toAjax(appDeviceShareService.deviceShare(bo));
}
/**
* 移除分享用户
*
* @param ids 主键串
*/
@DeleteMapping("/{ids}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(appDeviceShareService.remove(ids));
}
/**
* 短信验证码
*
* @param phonenumber 用户手机号
*/
@SaIgnore
@RateLimiter(key = "#phonenumber", time = 60, count = 1)
@GetMapping("/sms/code")
public R<Void> smsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = DEVICE_SHARE_CODES_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();
}
}

View File

@ -29,16 +29,16 @@ public class AppOperationVideoController extends BaseController {
* 查询操作视频列表
*/
@GetMapping("/listOperationVideos")
public List<AppOperationVideoVo> listOperationVideos(AppOperationVideoBo bo) {
return appOperationVideoService.queryList(bo);
public R<List<AppOperationVideoVo>> listOperationVideos(AppOperationVideoBo bo) {
return R.ok(appOperationVideoService.queryList(bo));
}
/**
* 查询操作视频详情信息
*/
@GetMapping("/getOperationVideoInfo")
public AppOperationVideoVo getOperationVideoInfo(AppOperationVideoBo bo) {
return appOperationVideoService.queryById(bo.getId());
public R<AppOperationVideoVo> getOperationVideoInfo(AppOperationVideoBo bo) {
return R.ok(appOperationVideoService.queryById(bo.getId()));
}
/**
@ -64,8 +64,8 @@ public class AppOperationVideoController extends BaseController {
/**
* 操作视频删除
*/
@DeleteMapping("/deleteOperationVideo")
public R<Void> deleteOperationVideo(Long[] ids) {
return toAjax(appOperationVideoService.deleteWithValidByIds(List.of(ids), true));
@DeleteMapping("/deleteOperationVideo/{id}")
public R<Void> deleteOperationVideo(@PathVariable Long id) {
return toAjax(appOperationVideoService.deleteWithValidByIds(List.of(id), true));
}
}

View File

@ -0,0 +1,88 @@
package com.fuyuanshen.app.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.fuyuanshen.app.domain.dto.APPForgotPasswordDTO;
import com.fuyuanshen.app.domain.dto.APPForgotPasswordSmsDTO;
import com.fuyuanshen.app.domain.dto.APPUpdateUserDTO;
import com.fuyuanshen.app.domain.vo.APPUserInfoVo;
import com.fuyuanshen.app.service.IAppUserService;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.ratelimiter.annotation.RateLimiter;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.web.core.BaseController;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
import java.util.LinkedHashMap;
/**
* APP 用户管理
* @date 2025-06-27
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {
private final IAppUserService appUserService;
/**
* 个人中心
*/
@GetMapping("/getUserInfo")
public R<APPUserInfoVo> getUserInfo() {
return R.ok(appUserService.getUserInfo());
}
/**
* 修改个人信息
*/
@PostMapping("/updateUser")
public R<Void> updateUser(@Validated @ModelAttribute APPUpdateUserDTO bo) {
return toAjax(appUserService.updateUser(bo));
}
/**
* 忘记密码
*/
@SaIgnore
@PostMapping("/forgotPassword")
public R<Void> forgotPassword(@RequestBody APPForgotPasswordDTO bo) {
return toAjax(appUserService.forgotPassword(bo));
}
/**
* 发送忘记密码短信
*
* @param phonenumber 用户手机号
*/
@SaIgnore
@RateLimiter(key = "#phonenumber", time = 60, count = 1)
@GetMapping("/sendForgotPasswordSms")
public R<Void> smsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
String key = GlobalConstants.APP_FORGOT_PASSWORD_SMS_KEY + phonenumber;
String code = RandomUtil.randomNumbers(4);
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
// 验证码模板id 自行处理 (查数据库或写死均可)
String templateId = "";
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();
}
}

View File

@ -0,0 +1,119 @@
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("/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,17 @@
package com.fuyuanshen.app.domain.dto;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
@Data
public class AppDeviceLogoUploadDto {
private Long deviceId;
private String deviceImei;
/**
* 文件
*/
private MultipartFile file;
}

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;
/**
* 设备类型
*/
private String typeName;
/**
* 功能类型
*/
private String functionMode;
/**
* 批次号
*/
private String batchId;
}

View File

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

View File

@ -22,4 +22,5 @@ public class AppSmsLoginBody {
*/
@NotBlank(message = "租户ID不能为空")
private String tenantId;
}

View File

@ -51,7 +51,7 @@ public class AppLoginService {
private Integer lockTime;
private final ISysTenantService tenantService;
private final IAppRoleService roleService;
private final IAppUserService appUserService;
/**
@ -185,4 +185,24 @@ public class AppLoginService {
}
}
public void cancelAccount() {
try {
AppLoginUser loginUser = AppLoginHelper.getLoginUser();
if (ObjectUtil.isNull(loginUser)) {
return;
}
appUserService.deleteWithValidByIds(Collections.singletonList(loginUser.getUserId()),true);
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,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,46 @@
package com.fuyuanshen.global.mqtt.base;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
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));
return true;
}
return false;
}
}

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,12 +7,7 @@ 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

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,8 @@
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 +15,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

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,12 +12,6 @@ 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 {
@ -44,7 +38,7 @@ public class MqttOutboundConfiguration {
mqttPahoClientFactory
);
mqttPahoMessageHandler.setDefaultQos(1);
mqttPahoMessageHandler.setDefaultTopic("worker/location");
mqttPahoMessageHandler.setDefaultTopic("B/#");
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

View File

@ -0,0 +1,50 @@
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";
}

View File

@ -0,0 +1,55 @@
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

@ -0,0 +1,16 @@
package com.fuyuanshen.global.mqtt.constants;
public interface MqttConstants {
/**
* 全局发布消息的key
*/
String GLOBAL_PUB_KEY = "B/";
/**
* 全局订阅消息的key
*/
String GLOBAL_SUB_KEY = "A/";
}

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,38 @@
package com.fuyuanshen.global.mqtt.listener;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.time.Duration;
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.FUNCTION_ACCESS_TIMEOUT_KEY;
@Component
@Slf4j
public class RedisKeyExpirationListener implements MessageListener {
@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);
}
}
/**
* 访问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,4 +1,4 @@
package com.fuyuanshen.system.mqtt.publish;
package com.fuyuanshen.global.mqtt.publish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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;

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,73 @@
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.constants.DeviceRedisKeyConstants;
import lombok.extern.slf4j.Slf4j;
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;
@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];
if(StringUtils.isNotBlank(deviceImei)){
//在线状态
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(62));
}
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);
}
}
}
}

View File

@ -0,0 +1,99 @@
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) {
CompletableFuture.runAsync(() -> {
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,56 @@
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 java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqAlarmRule implements MqttMessageRule {
@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;
// 存储到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,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,80 @@
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.DEVICE_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_LIGHT_MODE_KEY_PREFIX;
/**
* 灯光模式订阅设备回传消息
*/
@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 mainLightMode = convertArr[1].toString();
if(StringUtils.isNotBlank(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", Duration.ofSeconds(60*15));
}
// 发送设备状态和位置信息到Redis
syncSendDeviceDataToRedisWithFuture(context.getDeviceImei(),mainLightMode);
}
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_LIGHT_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,215 @@
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.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;
@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();
// 异步发送经纬度到Redis
asyncSendLocationToRedisWithFuture(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) {
CompletableFuture.runAsync(() -> {
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);
}
});
}
/**
* 存储设备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,84 @@
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 java.util.concurrent.CompletableFuture;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
/**
* 灯光模式订阅设备回传消息
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqModeRule implements MqttMessageRule {
@Override
public String getCommandType() {
return LightingCommandTypeConstants.LIGHT_MODE;
}
@Override
public void execute(MqttRuleContext context) {
String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
try {
Object[] convertArr = context.getConvertArr();
String mainLightMode = convertArr[1].toString();
String batteryRemainingTime = convertArr[2].toString();
if(StringUtils.isNotBlank(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", Duration.ofSeconds(60*15));
}
// 发送设备状态和位置信息到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);
}
}
}

View File

@ -0,0 +1,58 @@
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.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.*;
/**
* 定位数据命令处理
*/
@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,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_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];
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() + ":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((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("发送设备信息数据到设备消息=>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,102 @@
package com.fuyuanshen.mp.controller;
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 com.fuyuanshen.app.model.AppSmsLoginBody;
import com.fuyuanshen.app.service.AppLoginService;
import com.fuyuanshen.common.core.constant.SystemConstants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.domain.model.AppLoginUser;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.domain.model.SmsLoginBody;
import com.fuyuanshen.common.core.utils.*;
import com.fuyuanshen.common.encrypt.annotation.ApiEncrypt;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.equipment.domain.UserApp;
import com.fuyuanshen.equipment.enums.AppUserTypeEnum;
import com.fuyuanshen.mp.domian.dto.AuthUserDto;
import com.fuyuanshen.mp.service.MPAuthService;
import com.fuyuanshen.mp.service.MPService;
import com.fuyuanshen.system.domain.bo.SysTenantBo;
import com.fuyuanshen.system.domain.vo.SysClientVo;
import com.fuyuanshen.system.domain.vo.SysTenantVo;
import com.fuyuanshen.system.domain.vo.SysUserVo;
import com.fuyuanshen.system.service.ISysClientService;
import com.fuyuanshen.system.service.ISysConfigService;
import com.fuyuanshen.system.service.ISysTenantService;
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 io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* APP认证
*
* @author Lion Li
*/
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/mp")
public class MPAuthController {
private final AppLoginService loginService;
private final SysRegisterService registerService;
private final ISysConfigService configService;
private final ISysTenantService tenantService;
private final ISysClientService clientService;
private final MPAuthService mpAuthService;
private final MPService mpService;
@Operation(summary = "小程序登录授权")
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
Long phoneNumber = authUser.getPhoneNumber();
// 判断小程序用户是否存在,不存在创建
UserApp mpUser = mpService.getMpUser(phoneNumber);
if (mpUser == null) {
RegisterBody registerBody = new RegisterBody();
registerBody.setUsername(phoneNumber.toString());
registerBody.setUserType(AppUserTypeEnum.XCX_USER.getCode());
registerBody.setTenantId("894078");
registerBody.setPassword("123456");
mpAuthService.register(registerBody);
}
// 去登录
SysClientVo client = clientService.queryByClientId("ca839698e245d60aa2f0e59bd52b34f8");
UserApp user = mpService.loadUserByUsername(phoneNumber.toString());
LoginUser loginUser = mpAuthService.buildLoginUser(user);
LoginVo login = mpAuthService.login(loginUser, client);
// 返回登录信息
return ResponseEntity.ok(login);
}
}

View File

@ -0,0 +1,37 @@
package com.fuyuanshen.mp.controller;
import cn.dev33.satoken.annotation.SaIgnore;
import com.fuyuanshen.common.core.domain.ResponseVO;
import com.fuyuanshen.equipment.service.DeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: 默苍璃
* @date: 2025-07-1208:36
*/
@Slf4j
@RestController
@RequestMapping("/mp")
@RequiredArgsConstructor
@Tag(name = "小程序:相关接口")
@SaIgnore
public class MPController {
private final DeviceService deviceService;
@GetMapping("/queryDevice")
@Operation(summary = "检查是否存在设备MAC号")
public ResponseVO<Boolean> queryDevice(@Parameter(name = "设备mac值") String mac) {
return ResponseVO.success(deviceService.queryDevice(mac));
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2019-2025 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fuyuanshen.mp.domian.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
/**
* @author Zheng Jie
* @date 2018-11-30
*/
@Getter
@Setter
public class AuthUserDto {
@Schema(name = "用户名")
private String username;
@Schema(name = "手机号APP/小程序 登录)")
private Long phoneNumber;
@Schema(name = "密码")
private String password;
@Schema(name = "验证码")
private String code;
@Schema(name = "验证码的key")
private String uuid = "";
}

View File

@ -0,0 +1,8 @@
package com.fuyuanshen.mp.mapper;
/**
* @author: 默苍璃
* @date: 2025-07-1210:16
*/
public interface MPMapper {
}

View File

@ -0,0 +1,164 @@
package com.fuyuanshen.mp.service;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.app.service.IAppRoleService;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.SystemConstants;
import com.fuyuanshen.common.core.constant.TenantConstants;
import com.fuyuanshen.common.core.domain.dto.PostDTO;
import com.fuyuanshen.common.core.domain.dto.RoleDTO;
import com.fuyuanshen.common.core.domain.model.AppLoginUser;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.domain.model.PasswordLoginBody;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.enums.LoginType;
import com.fuyuanshen.common.core.enums.UserType;
import com.fuyuanshen.common.core.exception.user.UserException;
import com.fuyuanshen.common.core.utils.*;
import com.fuyuanshen.common.json.utils.JsonUtils;
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.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.domain.UserApp;
import com.fuyuanshen.equipment.service.AppUserService;
import com.fuyuanshen.system.domain.SysUser;
import com.fuyuanshen.system.domain.bo.SysUserBo;
import com.fuyuanshen.system.domain.vo.*;
import com.fuyuanshen.system.service.ISysTenantService;
import com.fuyuanshen.system.service.ISysUserService;
import com.fuyuanshen.web.domain.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.*;
import java.util.function.Supplier;
/**
* 登录校验方法
*
* @author Lion Li
*/
@RequiredArgsConstructor
@Slf4j
@Service
public class MPAuthService {
private final ISysUserService userService;
private final AppUserService appUserService;
/**
* 小程序注册
*/
public void register(RegisterBody registerBody) {
String tenantId = registerBody.getTenantId();
String username = registerBody.getUsername();
String password = registerBody.getPassword();
// 校验用户类型是否存在
String userType = UserType.getUserType(registerBody.getUserType()).getUserType();
UserApp sysUser = new UserApp();
sysUser.setUserName(username);
sysUser.setNickName(username);
sysUser.setPhonenumber(username);
sysUser.setTenantId(tenantId);
sysUser.setUserType(registerBody.getUserType());
sysUser.setPassword(BCrypt.hashpw(password));
sysUser.setUserType(userType);
appUserService.saveMpUser(sysUser);
}
/**
* 记录登录信息
*
* @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());
// com.fuyuanshen.web.listener.UserActionListener
SpringUtils.context().publishEvent(logininforEvent);
}
public LoginVo login(LoginUser loginUser, SysClientVo client) {
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = new SaLoginParameter();
model.setDeviceType(client.getDeviceType());
// 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
// 例如: 后台用户30分钟过期 app用户1天过期
model.setTimeout(client.getTimeout());
model.setActiveTimeout(client.getActiveTimeout());
model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
/**
* 构建登录用户
*/
public LoginUser buildLoginUser(UserApp user) {
LoginUser loginUser = new LoginUser();
Long userId = user.getUserId();
loginUser.setTenantId(user.getTenantId());
loginUser.setUserId(userId);
loginUser.setDeptId(user.getDeptId());
loginUser.setUsername(user.getUserName());
loginUser.setNickname(user.getNickName());
loginUser.setUserType(user.getUserType());
// 用户级别
// loginUser.setUserLevel(user.getUserLevel());
// pid
// loginUser.setPid(user.getPid());
// loginUser.setMenuPermission(permissionService.getMenuPermission(userId));
// loginUser.setRolePermission(permissionService.getRolePermission(userId));
// if (ObjectUtil.isNotNull(user.getDeptId())) {
// Opt<SysDeptVo> deptOpt = Opt.of(user.getDeptId()).map(deptService::selectDeptById);
// loginUser.setDeptName(deptOpt.map(SysDeptVo::getDeptName).orElse(StringUtils.EMPTY));
// loginUser.setDeptCategory(deptOpt.map(SysDeptVo::getDeptCategory).orElse(StringUtils.EMPTY));
// }
// List<SysRoleVo> roles = roleService.selectRolesByUserId(userId);
// // List<SysPostVo> posts = postService.selectPostsByUserId(userId);
// loginUser.setRoles(BeanUtil.copyToList(roles, RoleDTO.class));
// loginUser.setPosts(BeanUtil.copyToList(posts, PostDTO.class));
return loginUser;
}
}

View File

@ -0,0 +1,26 @@
package com.fuyuanshen.mp.service;
import com.fuyuanshen.equipment.domain.UserApp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 登录校验方法
*
* @author Lion Li
*/
public interface MPService {
/**
* 获取小程序用户信息
*
* @param phoneNumber 手机号
*/
UserApp getMpUser(Long phoneNumber);
UserApp loadUserByUsername(String username);
}

View File

@ -0,0 +1,12 @@
package com.fuyuanshen.mp.service.impl;
/**
* 登录校验方法
*
* @author Lion Li
*/
public class MPAuthServiceImpl {
}

View File

@ -0,0 +1,43 @@
package com.fuyuanshen.mp.service.impl;
import com.fuyuanshen.equipment.domain.UserApp;
import com.fuyuanshen.equipment.mapper.UserAppMapper;
import com.fuyuanshen.equipment.service.AppUserService;
import com.fuyuanshen.mp.service.MPService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 登录校验方法
*
* @author Lion Li
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class MPServiceImpl implements MPService {
private final AppUserService appUserService;
/**
* 获取小程序用户信息
*
* @param phoneNumber 手机号
*/
@Override
public UserApp getMpUser(Long phoneNumber) {
return appUserService.getMpUser(phoneNumber);
}
@Override
public UserApp loadUserByUsername(String username) {
return appUserService.loadUserByUsername(username);
}
}

View File

@ -0,0 +1,64 @@
package com.fuyuanshen.web;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ChineseVCardGenerator {
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"
};
// 创建.vcf文件
String filename = "上饶联系人.vcf";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true))) {
// 添加文件头信息(包含中文)
writer.write("BEGIN:VCARD");
writer.newLine();
writer.write("VERSION:3.0");
writer.newLine();
writer.write("X-GENERATOR:Java VCard Generator");
writer.newLine();
writer.write("PRODID:-//Apple Inc.//iPhone OS 15.6//EN");
writer.newLine();
writer.newLine();
// 生成所有联系人
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";
// 写入单个联系人(使用中文)
writer.write("FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:用户" + (count + 1)); // 中文姓名
writer.newLine();
writer.write("TEL;TYPE=CELL;CHARSET=UTF-8:" + phoneNumber); // 手机号
writer.newLine();
writer.write("NOTE;CHARSET=UTF-8:生成时间 " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
writer.newLine();
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

@ -0,0 +1,41 @@
package com.fuyuanshen.web;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class PhoneNumberGenerator {
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"
};
// 输出到控制台
System.out.println("江西上饶134号段完整手机号码共2200个");
for (String prefix : prefixes) {
for (int i = 0; i < 100; i++) {
String middle = String.format("%02d", i); // 生成00-99的中间数字
System.out.println(prefix + middle + "51");
}
}
// 同时输出到文件(可选)
try (BufferedWriter writer = new BufferedWriter(new FileWriter("shangrao_phones.txt"))) {
for (String prefix : prefixes) {
for (int i = 0; i < 100; i++) {
String middle = String.format("%02d", i);
writer.write(prefix + middle + "51");
writer.newLine();
}
}
System.out.println("\n同时已保存到文件shangrao_phones.txt");
} catch (IOException e) {
System.err.println("文件写入错误:" + e.getMessage());
}
}
}

View File

@ -0,0 +1,59 @@
package com.fuyuanshen.web;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class VCardGenerator {
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"
};
// 创建.vcf文件
String filename = "shangrao_contacts.vcf";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
// 写入文件头
writer.write("BEGIN:VCARD");
writer.newLine();
writer.write("VERSION:3.0");
writer.newLine();
writer.newLine();
// 生成所有联系人
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";
// 写入单个联系人
writer.write("FN:" + phoneNumber); // 姓名字段使用手机号
writer.newLine();
writer.write("TEL;TYPE=CELL:" + phoneNumber); // 电话字段使用手机号
writer.newLine();
writer.write("END:VCARD");
writer.newLine();
writer.newLine();
count++;
}
}
// 写入文件尾
writer.write("END:VCARD");
System.out.println("成功生成 " + count + " 个联系人");
System.out.println("文件已保存为: " + filename);
} catch (IOException e) {
System.err.println("文件写入错误: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,61 @@
//package com.fuyuanshen.web.config;
//
//import cn.hutool.core.lang.UUID;
//import com.fuyuanshen.global.mqtt.config.MqttPropertiesConfig;
//import com.fuyuanshen.web.handler.mqtt.DeviceReceiverMessageHandler;
//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;
//
///**
// * @author: 默苍璃
// * @date: 2025-08-0110:46
// */
//@Configuration
//public class CustomMqttInboundConfiguration {
//
// @Autowired
// private MqttPropertiesConfig mqttPropertiesConfig;
// @Autowired
// private MqttPahoClientFactory mqttPahoClientFactory;
// @Autowired
// private DeviceReceiverMessageHandler deviceReceiverMessageHandler;
//
//
// @Bean
// public MessageChannel customMqttChannel(){
// return new DirectChannel();
// }
//
//
// @Bean
// public MessageProducer customMessageProducer(){
// String clientId = "custom_client_" + UUID.fastUUID();
// MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
// mqttPropertiesConfig.getUrl(),
// clientId,
// mqttPahoClientFactory,
// "A/#", "B/#" // 直接指定这两个主题
// );
// adapter.setQos(1);
// adapter.setConverter(new DefaultPahoMessageConverter());
// adapter.setOutputChannel(customMqttChannel());
// return adapter;
// }
//
//
// @Bean
// @ServiceActivator(inputChannel = "customMqttChannel")
// public MessageHandler customMessageHandler(){
// return deviceReceiverMessageHandler;
// }
//
//}

View File

@ -111,6 +111,7 @@ public class AuthController {
return R.ok(loginVo);
}
/**
* 获取跳转URL
*
@ -133,6 +134,7 @@ public class AuthController {
return R.ok("操作成功", authorizeUrl);
}
/**
* 前端回调绑定授权(需要token)
*

View File

@ -67,7 +67,7 @@ public class CaptchaController {
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
map.put("code", code);
SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, map);
if (!smsResponse.isSuccess()) {
log.error("验证码短信发送异常 => {}", smsResponse);
return R.fail(smsResponse.getData().toString());

View File

@ -0,0 +1,119 @@
package com.fuyuanshen.web.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("/api/bjq/device")
public class DeviceBJQController 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,210 @@
package com.fuyuanshen.web.controller.device;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: 默苍璃
* @date: 2025-08-0810:40
*/
@Slf4j
@Tag(name = "web后台:设备控制中心", description = "web后台:设备控制中心")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/device/controlCenter")
public class DeviceControlCenterController {
/**
* 获取设备基本信息
* @param deviceId 设备ID
* @return 设备基本信息
*/
@GetMapping("/info/{deviceId}")
public ResponseEntity<Map<String, Object>> getDeviceInfo(@PathVariable String deviceId) {
// 实际应用中这里会从数据库查询设备信息
Map<String, Object> deviceInfo = new HashMap<>();
deviceInfo.put("deviceName", "6170零零一");
deviceInfo.put("deviceModel", "BJQ6170");
deviceInfo.put("deviceId", deviceId);
deviceInfo.put("status", "在线");
deviceInfo.put("batteryLevel", 85);
return ResponseEntity.ok(deviceInfo);
}
/**
* 设置灯光模式
* @param lightModeRequest 灯光模式请求
* @return 操作结果
*/
@PostMapping("/light-mode")
public ResponseEntity<Map<String, Object>> setLightMode(@RequestBody LightModeRequest lightModeRequest) {
// 实际应用中这里会控制设备灯光
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
// response.put("message", "灯光模式已设置为: " + lightModeRequest.getMode());
// response.put("deviceId", lightModeRequest.getDeviceId());
// response.put("mode", lightModeRequest.getMode());
return ResponseEntity.ok(response);
}
/**
* 更新人员信息
* @param personInfo 人员信息
* @return 操作结果
*/
@PostMapping("/person-info")
public ResponseEntity<Map<String, Object>> updatePersonInfo(@RequestBody PersonInfo personInfo) {
// 实际应用中这里会更新数据库
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "人员信息已更新");
// response.put("unit", personInfo.getUnit());
// response.put("position", personInfo.getPosition());
return ResponseEntity.ok(response);
}
/**
* 管理开机画面内容
* @param bootScreenRequest 开机画面请求
* @return 操作结果
*/
@PostMapping("/boot-screen")
public ResponseEntity<Map<String, Object>> manageBootScreen(@RequestBody BootScreenRequest bootScreenRequest) {
// 实际应用中这里会更新设备开机画面
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "开机画面内容已更新");
// response.put("deviceId", bootScreenRequest.getDeviceId());
// response.put("screens", bootScreenRequest.getScreens());
return ResponseEntity.ok(response);
}
/**
* 设置灯光亮度
* @param brightnessRequest 亮度请求
* @return 操作结果
*/
@PostMapping("/brightness")
public ResponseEntity<Map<String, Object>> setBrightness(@RequestBody BrightnessRequest brightnessRequest) {
// 实际应用中这里会控制设备亮度
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
// response.put("message", "灯光亮度已设置为: " + brightnessRequest.getBrightness() + "%");
// response.put("deviceId", brightnessRequest.getDeviceId());
// response.put("brightness", brightnessRequest.getBrightness());
// response.put("forceAlarm", brightnessRequest.isForceAlarm());
return ResponseEntity.ok(response);
}
/**
* 获取设备位置信息
* @param deviceId 设备ID
* @return 位置信息
*/
@GetMapping("/location/{deviceId}")
public ResponseEntity<Map<String, Object>> getLocation(@PathVariable String deviceId) {
// 实际应用中这里会从设备获取实时位置
Map<String, Object> locationInfo = new HashMap<>();
locationInfo.put("deviceId", deviceId);
locationInfo.put("longitude", "114°7'E");
locationInfo.put("latitude", "30'28'N");
locationInfo.put("address", "湖北省武汉市洪山区光谷大道国际企业中心");
locationInfo.put("timestamp", new Date());
return ResponseEntity.ok(locationInfo);
}
/**
* 发送紧急消息
* @param messageRequest 消息请求
* @return 操作结果
*/
@PostMapping("/send-message")
public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody MessageRequest messageRequest) {
// 实际应用中这里会向设备发送消息
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "消息已发送");
// response.put("deviceId", messageRequest.getDeviceId());
// response.put("content", messageRequest.getContent());
response.put("timestamp", new Date());
return ResponseEntity.ok(response);
}
/**
* 管理操作视频
* @param videoRequest 视频请求
* @return 操作结果
*/
@PostMapping("/operation-video")
public ResponseEntity<Map<String, Object>> manageOperationVideo(@RequestBody VideoRequest videoRequest) {
// 实际应用中这里会更新设备操作视频
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "操作视频已更新");
// response.put("deviceId", videoRequest.getDeviceId());
// response.put("videoUrl", videoRequest.getVideoUrl());
return ResponseEntity.ok(response);
}
// 请求对象类定义
public static class LightModeRequest {
private String deviceId;
private String mode; // 强光、弱光、爆闪、泛光、激光
// Getters and Setters
}
public static class PersonInfo {
private String deviceId;
private String unit; // 单位
private String position; // 职位
// Getters and Setters
}
public static class BootScreenRequest {
private String deviceId;
private List<String> screens; // 产品参数、操作说明等
// Getters and Setters
}
public static class BrightnessRequest {
private String deviceId;
private int brightness; // 0-100
private boolean forceAlarm; // 强制报警
// Getters and Setters
}
public static class MessageRequest {
private String deviceId;
private String content; // 消息内容
// Getters and Setters
}
public static class VideoRequest {
private String deviceId;
private String videoUrl; // 视频链接
// Getters and Setters
}
}

View File

@ -0,0 +1,109 @@
package com.fuyuanshen.web.controller.device;
import java.util.List;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.fuyuanshen.common.idempotent.annotation.RepeatSubmit;
import com.fuyuanshen.common.log.annotation.Log;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.core.validate.EditGroup;
import com.fuyuanshen.common.log.enums.BusinessType;
import com.fuyuanshen.common.excel.utils.ExcelUtil;
import com.fuyuanshen.equipment.domain.vo.DeviceGroupVo;
import com.fuyuanshen.equipment.domain.bo.DeviceGroupBo;
import com.fuyuanshen.equipment.service.IDeviceGroupService;
/**
* 设备分组
*
* @author Lion Li
* @date 2025-08-08
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/device/group")
public class DeviceGroupController extends BaseController {
private final IDeviceGroupService deviceGroupService;
/**
* 查询设备分组列表
*/
@SaCheckPermission("fys-equipment:group:list")
@GetMapping("/list")
public R<List<DeviceGroupVo>> list(DeviceGroupBo bo) {
List<DeviceGroupVo> list = deviceGroupService.queryList(bo);
return R.ok(list);
}
/**
* 导出设备分组列表
*/
@SaCheckPermission("fys-equipment:group:export")
@Log(title = "设备分组", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(DeviceGroupBo bo, HttpServletResponse response) {
List<DeviceGroupVo> list = deviceGroupService.queryList(bo);
ExcelUtil.exportExcel(list, "设备分组", DeviceGroupVo.class, response);
}
/**
* 获取设备分组详细信息
*
* @param id 主键
*/
@SaCheckPermission("fys-equipment:group:query")
@GetMapping("/{id}")
public R<DeviceGroupVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
return R.ok(deviceGroupService.queryById(id));
}
/**
* 新增设备分组
*/
@SaCheckPermission("fys-equipment:group:add")
@Log(title = "设备分组", businessType = BusinessType.INSERT)
@RepeatSubmit()
@PostMapping()
public R<Void> add(@Validated(AddGroup.class) @RequestBody DeviceGroupBo bo) {
return toAjax(deviceGroupService.insertByBo(bo));
}
/**
* 修改设备分组
*/
@SaCheckPermission("fys-equipment:group:edit")
@Log(title = "设备分组", businessType = BusinessType.UPDATE)
@RepeatSubmit()
@PutMapping()
public R<Void> edit(@Validated(EditGroup.class) @RequestBody DeviceGroupBo bo) {
return toAjax(deviceGroupService.updateByBo(bo));
}
/**
* 删除设备分组
*
* @param ids 主键串
*/
@SaCheckPermission("fys-equipment:group:remove")
@Log(title = "设备分组", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
return toAjax(deviceGroupService.deleteWithValidByIds(List.of(ids), true));
}
}

View File

@ -0,0 +1,118 @@
package com.fuyuanshen.web.controller.device;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.web.service.WEBDeviceService;
import com.fuyuanshen.web.service.device.DeviceBizService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @Description:
* @Author: WY
* @Date: 2025/5/16
**/
@Slf4j
@Tag(name = "web:设备管理", description = "web:设备管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/device")
public class WEBDeviceController extends BaseController {
private final WEBDeviceService deviceService;
private final DeviceBizService appDeviceService;
/**
* @param id
* @return
* @ModelAttribute 主要用于将请求参数绑定到 Java 对象上,它会从 HTTP 请求的查询参数Query Parameters
* 或表单数据Form Data中提取值并自动填充到指定的对象属性中。
*/
// @Log("解绑设备")
@Operation(summary = "WEB端解绑设备")
@DeleteMapping(value = "/unbind")
public R<Void> unbindDevice(Long id, Long userId) {
return toAjax(deviceService.webUnBindDevice(id, userId));
}
/**
* 查询设备列表
*/
@GetMapping("/list")
public TableDataInfo<AppDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return appDeviceService.queryAppDeviceList(bo, pageQuery);
}
/**
* 绑定设备
*/
@PostMapping("/bind")
public R<Void> bind(@RequestBody AppDeviceBo bo) {
return toAjax(appDeviceService.bindDevice(bo));
}
/**
* 解绑设备
*/
@DeleteMapping("/unBind")
public R<Void> unBind(Long id) {
return toAjax(appDeviceService.unBindDevice(id));
}
/**
* 查询设备类型列表
*/
@GetMapping(value = "/typeList")
public R<List<APPDeviceTypeVo>> getTypeList() {
List<APPDeviceTypeVo> typeList = appDeviceService.getTypeList();
return R.ok(typeList);
}
/**
* 重命名设备
*
* @param reNameDTO
* @return
*/
@PostMapping(value = "/reName")
public R<String> reName(@Validated @RequestBody APPReNameDTO reNameDTO) {
appDeviceService.reName(reNameDTO);
return R.ok("重命名成功!!!");
}
@GetMapping("/realTimeStatus")
public R<Map<String, Object>> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
Map<String, Object> status = appDeviceService.getRealTimeStatus(statusDto);
return R.ok(status);
}
/**
* 根据mac查询设备信息
*/
@GetMapping("/getDeviceInfoByDeviceMac")
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
}
}

View File

@ -0,0 +1,50 @@
package com.fuyuanshen.web.enums;
/**
* @author: 默苍璃
* @date: 2025-08-0114:14
*/
public enum InstructType6170 {
EQUIPMENT_REPORTING(0, "设备启动"),
LIGHT_MODE(1, "灯光模式"),
/**
* 设备信息
* 单位/姓名/职位
*/
UNIT_INFO(2, "设备信息"),
BOOT_IMAGE(3, "开机图片"),
LASER_LIGHT(4, "激光灯"),
BRIGHTNESS(5, "亮度调节"),
LOCATION_DATA(11, "定位数据"),
UNKNOWN(-1, "未知操作");
private final int code;
private final String description;
InstructType6170(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public static InstructType6170 fromCode(int code) {
for (InstructType6170 type : values()) {
if (type.getCode() == code) {
return type;
}
}
// throw new IllegalArgumentException("未知的指令类型代码: " + code);
return UNKNOWN;
}
}

View File

@ -0,0 +1,45 @@
package com.fuyuanshen.web.enums;
/**
* @author: 默苍璃
* @date: 2025-08-0114:30
*/
public enum LightModeEnum6170 {
OFF(0, "关灯"),
HIGH_BEAM(1, "强光模式"),
LOW_BEAM(2, "弱光模式"),
STROBE(3, "爆闪模式"),
FLOOD(4, "泛光模式"),
UNKNOWN(-1, "未知的灯光模式");
private final int code;
private final String description;
LightModeEnum6170(int code, String description) {
this.code = code;
this.description = description;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public static LightModeEnum6170 fromCode(int code) {
for (LightModeEnum6170 mode : values()) {
if (mode.getCode() == code) {
return mode;
}
}
// throw new IllegalArgumentException("未知的灯光模式代码: " + code);
return UNKNOWN;
}
}

View File

@ -0,0 +1,318 @@
//package com.fuyuanshen.web.handler.mqtt;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fuyuanshen.common.satoken.utils.LoginHelper;
//import com.fuyuanshen.equipment.domain.Device;
//import com.fuyuanshen.equipment.domain.DeviceLog;
//import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
//import com.fuyuanshen.equipment.mapper.DeviceMapper;
//import com.fuyuanshen.equipment.utils.map.GetAddressFromLatUtil;
//import com.fuyuanshen.equipment.utils.map.LngLonUtil;
//import com.fuyuanshen.global.mqtt.constants.TenantsConstant;
//import com.fuyuanshen.web.enums.InstructType6170;
//import com.fuyuanshen.web.enums.LightModeEnum6170;
//import lombok.AllArgsConstructor;
//import lombok.Data;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.messaging.Message;
//import org.springframework.messaging.MessageHandler;
//import org.springframework.messaging.MessageHeaders;
//import org.springframework.messaging.MessagingException;
//import org.springframework.stereotype.Component;
//
///**
// * 定义监听主题消息的处理器
// *
// * @author: 默苍璃
// * @date: 2025-08-0110:19
// */
//@Component
//@Data
//@AllArgsConstructor
//@Slf4j
//public class DeviceReceiverMessageHandler implements MessageHandler {
//
// private final DeviceMapper deviceMapper;
// private final DeviceLogMapper deviceLogMapper;
//
// // 使用Jackson解析JSON
// private static final ObjectMapper objectMapper = new ObjectMapper();
//
//
// /**
// * 处理接收的消息
// *
// * @param message
// * @throws MessagingException
// */
// @Override
// public void handleMessage(Message<?> message) throws MessagingException {
// // System.out.println("接收到的消息:" + message.getPayload());
// MessageHeaders headers = message.getHeaders();
// String receivedTopicName = (String) headers.get("mqtt_receivedTopic");
// System.out.println("消息来自主题:" + receivedTopicName);
//
// // String tenantId = LoginHelper.getTenantId();
// String tenantId = TenantsConstant.FU_YUAN_SHENG;
// String payload = message.getPayload().toString();
//
// if (receivedTopicName != null) {
// // 1. 提取设备ID (从主题中获取)
// String deviceImei = extractDeviceId(receivedTopicName);
// Device device = deviceMapper.selectOne(new QueryWrapper<Device>()
// .eq("tenant_id", tenantId)
// .eq("device_imei", deviceImei));
// if (device == null) {
// log.info("不存在的设备IMEI: {}", deviceImei);
// } else {
//
// try {
// JsonNode root = objectMapper.readTree(payload);
//
// DeviceLog record = new DeviceLog();
// // 手动设置租户ID
// record.setTenantId(device.getTenantId()); // 从设备信息中获取租户ID
// // 设备ID
// record.setDeviceId(device.getId());
// // 设备名称
// record.setDeviceName(device.getDeviceName());
//
// // 2. 处理instruct消息
// if (root.has("instruct")) {
// JsonNode instructNode = root.get("instruct");
// if (instructNode.isArray()) {
// boolean b = receivedTopicName.startsWith("B/");
// record = parseInstruct(device, instructNode, b);
// // 根据不同主题进行不同处理
// if (receivedTopicName.startsWith("A/")) {
// // 处理A主题的消息设备上传
// record.setDataSource("设备上报");
// } else if (receivedTopicName.startsWith("B/")) {
// // 处理B主题的消息 (手动上传)
// record.setDataSource("客户端操作");
// }
// }
// // 确保在插入前设置tenantId和deviceId
// record.setTenantId(device.getTenantId());
// record.setDeviceId(device.getId());
// deviceLogMapper.insert(record);
// }
//
// // 2. 处理 state 消息
// if (root.has("state")) {
// JsonNode instructNode = root.get("state");
// if (instructNode.isArray()) {
// boolean b = receivedTopicName.startsWith("B/");
// record = parseState(device, instructNode, b);
// // 根据不同主题进行不同处理
// if (receivedTopicName.startsWith("A/")) {
// // 处理A主题的消息设备上传
// record.setDataSource("设备上报");
// } else if (receivedTopicName.startsWith("B/")) {
// // 处理B主题的消息 (手动上传)
// record.setDataSource("客户端操作");
// }
// }
// // 确保在插入前设置tenantId和deviceId
// record.setTenantId(device.getTenantId());
// record.setDeviceId(device.getId());
// deviceLogMapper.insert(record);
// }
//
// if (root.has("imei")) {
// // 设备行为
// record.setDeviceAction(InstructType6170.fromCode(0).getDescription());
// record.setDataSource("设备上报");
// record.setContent("设备启动");
// // 确保在插入前设置tenantId和deviceId
// record.setTenantId(device.getTenantId());
// record.setDeviceId(device.getId());
// deviceLogMapper.insert(record);
// }
//
//
// // 3. 处理state消息
// // else if (root.has("state")) {
// // JsonNode stateNode = root.get("state");
// // if (stateNode.isArray()) {
// // StateRecord record = parseState(device, stateNode);
// // stateRepo.save(record);
// // }
// // }
// } catch (Exception e) {
// log.error("消息解析失败: {}", payload, e);
// }
//
// }
//
// }
// }
//
//
// /**
// * 从主题中提取设备ID(IMEI)
// *
// * @param topic
// * @return
// */
// private String extractDeviceId(String topic) {
// // 处理 A/# 或 B/# 格式的主题,例如 B/861556078765285 或 A/861556078765285
// String[] segments = topic.split("/");
// if (segments.length >= 2) {
// // 返回第二个段,即 / 后面的部分
// return segments[1];
// }
// // 如果格式不符合预期,返回原主题
// return topic;
// }
//
//
// /**
// * 解析instruct消息
// *
// * @param device
// * @param array
// * @param b
// * @return
// */
// private DeviceLog parseInstruct(Device device, JsonNode array, boolean b) {
// DeviceLog record = new DeviceLog();
// record.setDeviceName(device.getDeviceName());
// // 设备行为
// record.setDeviceAction(InstructType6170.fromCode(array.get(0).asInt()).getDescription());
//
// switch (array.get(0).asInt()) {
// case 1: // 灯光模式
// LightModeEnum6170 lightModeEnum6170 = LightModeEnum6170.fromCode(array.get(1).asInt());
// record.setContent(lightModeEnum6170.getDescription());
// break;
//
// case 2: // 单位/姓名/职位
// byte[] unitBytes = new byte[480];
// for (int i = 1; i <= 480; i++) {
// unitBytes[i - 1] = (byte) array.get(i).asInt();
// }
// // record.setUnitData(unitBytes);
// break;
//
// case 3: // 开机图片
// // record.setImagePage(array.get(1).asInt());
// byte[] imageBytes = new byte[512];
// for (int i = 2; i <= 513; i++) {
// imageBytes[i - 2] = (byte) array.get(i).asInt();
// }
// // record.setImageData(imageBytes);
// break;
//
// case 4: // 激光灯
// int anInt = array.get(1).asInt();
// if (anInt == 0) {
// record.setContent("关闭激光灯");
// } else if (anInt == 1) {
// record.setContent("开启激光灯");
// } else {
// record.setContent("未知操作");
// }
// break;
//
// case 5: // 亮度调节
// record.setContent(+array.get(1).asInt() + "%");
// break;
//
// case 11: // 定位数据
// if (b) {
// break;
// }
// int i1 = array.get(1).asInt();
// int i2 = array.get(2).asInt();
// int i3 = array.get(3).asInt();
// int i4 = array.get(4).asInt();
//
// // 优雅的转换方式 Longitude and latitude
// double latitude = i1 + i2 / 10.0;
// double Longitude = i3 + i4 / 10.0;
// // 84 ==》 高德
// double[] doubles = LngLonUtil.gps84_To_Gcj02(latitude, Longitude);
// String address = GetAddressFromLatUtil.getAdd(String.valueOf(doubles[1]), String.valueOf(doubles[0]));
// record.setContent(address);
// break;
// }
// return record;
// }
//
//
// /**
// * 解析 state 消息
// *
// * @param device
// * @param array
// * @return
// */
// private DeviceLog parseState(Device device, JsonNode array, boolean b) {
// DeviceLog record = new DeviceLog();
// record.setDeviceName(device.getDeviceName());
// // 设备行为
// record.setDeviceAction(InstructType6170.fromCode(array.get(0).asInt()).getDescription());
//
// switch (array.get(0).asInt()) {
// case 1: // 灯光模式
// LightModeEnum6170 lightModeEnum6170 = LightModeEnum6170.fromCode(array.get(1).asInt());
// record.setContent(lightModeEnum6170.getDescription());
// break;
//
// case 2: // 单位/姓名/职位
// byte[] unitBytes = new byte[480];
// for (int i = 1; i <= 480; i++) {
// unitBytes[i - 1] = (byte) array.get(i).asInt();
// }
// // record.setUnitData(unitBytes);
// break;
//
// case 3: // 开机图片
// // record.setImagePage(array.get(1).asInt());
// byte[] imageBytes = new byte[512];
// for (int i = 2; i <= 513; i++) {
// imageBytes[i - 2] = (byte) array.get(i).asInt();
// }
// // record.setImageData(imageBytes);
// break;
//
// case 4: // 激光灯
// int anInt = array.get(1).asInt();
// if (anInt == 0) {
// record.setContent("关闭激光灯");
// } else if (anInt == 1) {
// record.setContent("开启激光灯");
// } else {
// record.setContent("未知操作");
// }
// break;
//
// case 5: // 亮度调节
// record.setContent(+array.get(1).asInt() + "%");
// break;
//
// case 11: // 定位数据
// if (b) {
// break;
// }
// int i1 = array.get(1).asInt();
// int i2 = array.get(2).asInt();
// int i3 = array.get(3).asInt();
// int i4 = array.get(4).asInt();
//
// // 优雅的转换方式 Longitude and latitude
// double latitude = i1 + i2 / 10.0;
// double Longitude = i3 + i4 / 10.0;
// // 84 ==》 高德
// double[] doubles = LngLonUtil.gps84_To_Gcj02(latitude, Longitude);
// String address = GetAddressFromLatUtil.getAdd(String.valueOf(doubles[1]), String.valueOf(doubles[0]));
// record.setContent(address);
// break;
// }
// return record;
// }
//
//}

View File

@ -1,163 +1,163 @@
package com.fuyuanshen.web.listener;
import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fuyuanshen.common.core.constant.CacheConstants;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.domain.dto.UserOnlineDTO;
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.ip.AddressUtils;
import com.fuyuanshen.common.log.event.LogininforEvent;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.web.service.SysLoginService;
import org.springframework.stereotype.Component;
import java.time.Duration;
/**
* 用户行为 侦听器的实现
*
* @author Lion Li
*/
@RequiredArgsConstructor
@Component
@Slf4j
public class UserActionListener implements SaTokenListener {
private final SysLoginService loginService;
/**
* 每次登录时触发
*/
@Override
public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginParameter loginParameter) {
UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = ServletUtils.getClientIP();
UserOnlineDTO dto = new UserOnlineDTO();
dto.setIpaddr(ip);
dto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
dto.setBrowser(userAgent.getBrowser().getName());
dto.setOs(userAgent.getOs().getName());
dto.setLoginTime(System.currentTimeMillis());
dto.setTokenId(tokenValue);
String username = (String) loginParameter.getExtra(LoginHelper.USER_NAME_KEY);
String tenantId = (String) loginParameter.getExtra(LoginHelper.TENANT_KEY);
dto.setUserName(username);
dto.setClientKey((String) loginParameter.getExtra(LoginHelper.CLIENT_KEY));
dto.setDeviceType(loginParameter.getDeviceType());
dto.setDeptName((String) loginParameter.getExtra(LoginHelper.DEPT_NAME_KEY));
TenantHelper.dynamic(tenantId, () -> {
if(loginParameter.getTimeout() == -1) {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
} else {
RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(loginParameter.getTimeout()));
}
});
// 记录登录日志
LogininforEvent logininforEvent = new LogininforEvent();
logininforEvent.setTenantId(tenantId);
logininforEvent.setUsername(username);
logininforEvent.setStatus(Constants.LOGIN_SUCCESS);
logininforEvent.setMessage(MessageUtils.message("user.login.success"));
logininforEvent.setRequest(ServletUtils.getRequest());
SpringUtils.context().publishEvent(logininforEvent);
// 更新登录信息
loginService.recordLoginInfo((Long) loginParameter.getExtra(LoginHelper.USER_KEY), ip);
log.info("user doLogin, userId:{}, token:{}", loginId, tokenValue);
}
/**
* 每次注销时触发
*/
@Override
public void doLogout(String loginType, Object loginId, String tokenValue) {
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
TenantHelper.dynamic(tenantId, () -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
log.info("user doLogout, userId:{}, token:{}", loginId, tokenValue);
}
/**
* 每次被踢下线时触发
*/
@Override
public void doKickout(String loginType, Object loginId, String tokenValue) {
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
TenantHelper.dynamic(tenantId, () -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
log.info("user doKickout, userId:{}, token:{}", loginId, tokenValue);
}
/**
* 每次被顶下线时触发
*/
@Override
public void doReplaced(String loginType, Object loginId, String tokenValue) {
String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
TenantHelper.dynamic(tenantId, () -> {
RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
});
log.info("user doReplaced, userId:{}, token:{}", loginId, tokenValue);
}
/**
* 每次被封禁时触发
*/
@Override
public void doDisable(String loginType, Object loginId, String service, int level, long disableTime) {
}
/**
* 每次被解封时触发
*/
@Override
public void doUntieDisable(String loginType, Object loginId, String service) {
}
/**
* 每次打开二级认证时触发
*/
@Override
public void doOpenSafe(String loginType, String tokenValue, String service, long safeTime) {
}
/**
* 每次创建Session时触发
*/
@Override
public void doCloseSafe(String loginType, String tokenValue, String service) {
}
/**
* 每次创建Session时触发
*/
@Override
public void doCreateSession(String id) {
}
/**
* 每次注销Session时触发
*/
@Override
public void doLogoutSession(String id) {
}
/**
* 每次Token续期时触发
*/
@Override
public void doRenewTimeout(String tokenValue, Object loginId, long timeout) {
}
}
//package com.fuyuanshen.web.listener;
//
//import cn.dev33.satoken.listener.SaTokenListener;
//import cn.dev33.satoken.stp.StpUtil;
//import cn.dev33.satoken.stp.parameter.SaLoginParameter;
//import cn.hutool.core.convert.Convert;
//import cn.hutool.http.useragent.UserAgent;
//import cn.hutool.http.useragent.UserAgentUtil;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import com.fuyuanshen.common.core.constant.CacheConstants;
//import com.fuyuanshen.common.core.constant.Constants;
//import com.fuyuanshen.common.core.domain.dto.UserOnlineDTO;
//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.ip.AddressUtils;
//import com.fuyuanshen.common.log.event.LogininforEvent;
//import com.fuyuanshen.common.redis.utils.RedisUtils;
//import com.fuyuanshen.common.satoken.utils.LoginHelper;
//import com.fuyuanshen.common.tenant.helper.TenantHelper;
//import com.fuyuanshen.web.service.SysLoginService;
//import org.springframework.stereotype.Component;
//
//import java.time.Duration;
//
///**
// * 用户行为 侦听器的实现
// *
// * @author Lion Li
// */
//@RequiredArgsConstructor
//@Component
//@Slf4j
//public class UserActionListener implements SaTokenListener {
//
// private final SysLoginService loginService;
//
// /**
// * 每次登录时触发
// */
// @Override
// public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginParameter loginParameter) {
// UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
// String ip = ServletUtils.getClientIP();
// UserOnlineDTO dto = new UserOnlineDTO();
// dto.setIpaddr(ip);
// dto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
// dto.setBrowser(userAgent.getBrowser().getName());
// dto.setOs(userAgent.getOs().getName());
// dto.setLoginTime(System.currentTimeMillis());
// dto.setTokenId(tokenValue);
// String username = (String) loginParameter.getExtra(LoginHelper.USER_NAME_KEY);
// String tenantId = (String) loginParameter.getExtra(LoginHelper.TENANT_KEY);
// dto.setUserName(username);
// dto.setClientKey((String) loginParameter.getExtra(LoginHelper.CLIENT_KEY));
// dto.setDeviceType(loginParameter.getDeviceType());
// dto.setDeptName((String) loginParameter.getExtra(LoginHelper.DEPT_NAME_KEY));
// TenantHelper.dynamic(tenantId, () -> {
// if(loginParameter.getTimeout() == -1) {
// RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
// } else {
// RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(loginParameter.getTimeout()));
// }
// });
// // 记录登录日志
// LogininforEvent logininforEvent = new LogininforEvent();
// logininforEvent.setTenantId(tenantId);
// logininforEvent.setUsername(username);
// logininforEvent.setStatus(Constants.LOGIN_SUCCESS);
// logininforEvent.setMessage(MessageUtils.message("user.login.success"));
// logininforEvent.setRequest(ServletUtils.getRequest());
// SpringUtils.context().publishEvent(logininforEvent);
// // 更新登录信息
// loginService.recordLoginInfo((Long) loginParameter.getExtra(LoginHelper.USER_KEY), ip);
// log.info("user doLogin, userId:{}, token:{}", loginId, tokenValue);
// }
//
// /**
// * 每次注销时触发
// */
// @Override
// public void doLogout(String loginType, Object loginId, String tokenValue) {
// String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
// TenantHelper.dynamic(tenantId, () -> {
// RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
// });
// log.info("user doLogout, userId:{}, token:{}", loginId, tokenValue);
// }
//
// /**
// * 每次被踢下线时触发
// */
// @Override
// public void doKickout(String loginType, Object loginId, String tokenValue) {
// String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
// TenantHelper.dynamic(tenantId, () -> {
// RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
// });
// log.info("user doKickout, userId:{}, token:{}", loginId, tokenValue);
// }
//
// /**
// * 每次被顶下线时触发
// */
// @Override
// public void doReplaced(String loginType, Object loginId, String tokenValue) {
// String tenantId = Convert.toStr(StpUtil.getExtra(tokenValue, LoginHelper.TENANT_KEY));
// TenantHelper.dynamic(tenantId, () -> {
// RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
// });
// log.info("user doReplaced, userId:{}, token:{}", loginId, tokenValue);
// }
//
// /**
// * 每次被封禁时触发
// */
// @Override
// public void doDisable(String loginType, Object loginId, String service, int level, long disableTime) {
// }
//
// /**
// * 每次被解封时触发
// */
// @Override
// public void doUntieDisable(String loginType, Object loginId, String service) {
// }
//
// /**
// * 每次打开二级认证时触发
// */
// @Override
// public void doOpenSafe(String loginType, String tokenValue, String service, long safeTime) {
// }
//
// /**
// * 每次创建Session时触发
// */
// @Override
// public void doCloseSafe(String loginType, String tokenValue, String service) {
// }
//
// /**
// * 每次创建Session时触发
// */
// @Override
// public void doCreateSession(String id) {
// }
//
// /**
// * 每次注销Session时触发
// */
// @Override
// public void doLogoutSession(String id) {
// }
//
// /**
// * 每次Token续期时触发
// */
// @Override
// public void doRenewTimeout(String tokenValue, Object loginId, long timeout) {
// }
//}

View File

@ -0,0 +1,131 @@
package com.fuyuanshen.web.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fuyuanshen.app.domain.AppUser;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.AppSmsRegisterBody;
import com.fuyuanshen.common.core.enums.UserType;
import com.fuyuanshen.common.core.exception.BadRequestException;
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.tenant.helper.TenantHelper;
import com.fuyuanshen.common.web.config.properties.CaptchaProperties;
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 ISysUserService userService;
private final SysUserMapper userMapper;
private final CaptchaProperties captchaProperties;
private final AppUserMapper appUserMapper;
/**
* 注册
*/
public void register(AppSmsRegisterBody registerBody) {
String phoneNumber = registerBody.getPhoneNumber();
LambdaQueryWrapper<AppUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AppUser::getPhonenumber, phoneNumber);
wrapper.eq(AppUser::getUserType, UserType.APP_USER.getUserType());
AppUserVo appUserVo = appUserMapper.selectVoOne(wrapper);
if (appUserVo != null) {
throw new BadRequestException("该手机号已被注册");
}
String verificationCode = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phoneNumber);
if (verificationCode == null) {
throw new BadRequestException("验证码已过期");
}
if(!registerBody.getVerificationCode().equals(verificationCode)){
throw new BadRequestException("验证码错误");
}
String tenantId = registerBody.getTenantId();
String username = registerBody.getPhoneNumber();
String password = registerBody.getPassword();
AppUser appUser = new AppUser();
appUser.setUserName(username);
appUser.setNickName(username);
appUser.setPhonenumber(phoneNumber);
appUser.setPassword(password);
appUser.setUserType(UserType.APP_USER.getUserType());
appUser.setTenantId(tenantId);
appUser.setLoginIp(ServletUtils.getClientIP());
appUser.setStatus("0");
appUser.setDelFlag("0");
appUser.setCreateTime(new Date());
boolean exist = TenantHelper.dynamic(tenantId, () -> {
return appUserMapper.exists(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getUserName, appUser.getUserName()));
});
if (exist) {
throw new UserException("user.register.save.error", username);
}
appUserMapper.insert(appUser);
recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
public void validateCaptcha(String tenantId, String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha)) {
recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
/**
* 记录登录信息
*
* @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);
}
}

View File

@ -0,0 +1,235 @@
package com.fuyuanshen.web.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;
import com.fuyuanshen.app.domain.vo.AppDeviceShareDetailVo;
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.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
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;
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
@Service
public class DeviceShareService {
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(DeviceShareService::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(StringUtils.isNotBlank(onlineStatus)){
item.setOnlineStatus(1);
}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::getId, id);
List<AppDeviceShareVo> appDeviceShareVos = appDeviceShareMapper.selectVoList(queryWrapper);
if(appDeviceShareVos==null || appDeviceShareVos.isEmpty()){
return null;
}
AppDeviceShareVo shareVo = appDeviceShareVos.get(0);
AppDeviceShareDetailVo shareDetailVo = new AppDeviceShareDetailVo();
shareDetailVo.setId(shareVo.getId());
shareDetailVo.setDeviceId(shareVo.getDeviceId());
shareDetailVo.setPhonenumber(shareVo.getPhonenumber());
shareDetailVo.setPermission(shareVo.getPermission());
Device device = deviceMapper.selectById(shareVo.getDeviceId());
shareDetailVo.setDeviceName(device.getDeviceName());
shareDetailVo.setDeviceImei(device.getDeviceImei());
shareDetailVo.setDeviceMac(device.getDeviceMac());
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
if(deviceType!=null){
shareDetailVo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
}
shareDetailVo.setDevicePic(device.getDevicePic());
shareDetailVo.setTypeName(deviceType.getTypeName());
shareDetailVo.setBluetoothName(device.getBluetoothName());
shareDetailVo.setDeviceStatus(device.getDeviceStatus());
shareDetailVo.setSendMsg(device.getSendMsg());
LambdaQueryWrapper<AppPersonnelInfo> qw = new LambdaQueryWrapper<>();
qw.eq(AppPersonnelInfo::getDeviceId, device.getId());
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
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;
}
/**
* 校验短信验证码
*/
private boolean validateSmsCode(String tenantId, String phonenumber, String smsCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.DEVICE_SHARE_CODES_KEY + phonenumber);
if (StringUtils.isBlank(code)) {
throw new ServiceException("验证码失效");
}
return code.equals(smsCode);
}
public int deviceShare(AppDeviceShareBo bo) {
boolean flag = validateSmsCode(AppLoginHelper.getTenantId(), bo.getPhonenumber(), bo.getSmsCode());
if(!flag){
throw new ServiceException("验证码错误");
}
Device device = deviceMapper.selectById(bo.getDeviceId());
if(device==null){
throw new ServiceException("设备不存在");
}
Long userId = AppLoginHelper.getUserId();
LambdaQueryWrapper<AppDeviceShare> lqw = new LambdaQueryWrapper<>();
lqw.eq(AppDeviceShare::getDeviceId, bo.getDeviceId());
lqw.eq(AppDeviceShare::getPhonenumber, bo.getPhonenumber());
Long count = appDeviceShareMapper.selectCount(lqw);
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("update_time", new Date());
return appDeviceShareMapper.update(uw);
}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(DeviceShareService::buildDeviceStatus);
return TableDataInfo.build(result);
}
}

View File

@ -0,0 +1,32 @@
package com.fuyuanshen.web.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.domain.vo.CustomerVo;
import java.io.IOException;
import java.util.List;
/**
* @Description:
* @Author: WY
* @Date: 2025/5/16
**/
public interface WEBDeviceService extends IService<Device> {
/**
* WEB端解绑设备
*
* @param id
* @return
*/
int webUnBindDevice(Long id, Long userId);
}

View File

@ -0,0 +1,474 @@
package com.fuyuanshen.web.service.device;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
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.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.*;
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.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.enums.LightModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.buildArr;
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.generateFixedBitmapData;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceBJQBizService {
private final DeviceMapper deviceMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final MqttGateway mqttGateway;
private final DeviceLogMapper deviceLogMapper;
public int sendMessage(AppDeviceSendMsgBo bo) {
List<Long> deviceIds = bo.getDeviceIds();
if (deviceIds == null || deviceIds.isEmpty()) {
throw new ServiceException("请选择设备");
}
for (Long deviceId : deviceIds) {
Device device = deviceMapper.selectById(deviceId);
if (device == null) {
throw new ServiceException("设备不存在" + deviceId);
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
try {
ClassPathResource resource = new ClassPathResource("image/background.png");
InputStream inputStream = resource.getInputStream();
byte[] largeData = ImageWithTextGenerate.generate160x80ImageWithText2(bo.getSendMsg(), inputStream, 25600);
int[] ints = convertHexToDecimal(largeData);
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data" , Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data");
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
log.info("发送信息第0块数据大小: {} 字节",specificChunk.length);
ArrayList<Integer> intData = new ArrayList<>();
intData.add(6);
intData.add(1);
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送信息点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", deviceId)
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("send_msg", bo.getSendMsg());
deviceMapper.update(updateWrapper);
recordDeviceLog(deviceId, device.getDeviceName(), "发送信息", bo.getSendMsg(), AppLoginHelper.getUserId());
} catch (Exception e) {
log.info("发送信息设备发送信息失败:{}" ,deviceId);
throw new ServiceException("发送指令失败");
}
}
return 1;
}
/**
* 记录设备操作日志
* @param deviceId 设备ID
* @param content 日志内容
* @param operator 操作人
*/
private void recordDeviceLog(Long deviceId,String deviceName, String deviceAction, String content, Long operator) {
try {
// 创建设备日志实体
com.fuyuanshen.equipment.domain.DeviceLog deviceLog = new com.fuyuanshen.equipment.domain.DeviceLog();
deviceLog.setDeviceId(deviceId);
deviceLog.setDeviceAction(deviceAction);
deviceLog.setContent(content);
deviceLog.setCreateBy(operator);
deviceLog.setDeviceName(deviceName);
deviceLog.setCreateTime(new Date());
// 插入日志记录
deviceLogMapper.insert(deviceLog);
} catch (Exception e) {
log.error("记录设备操作日志失败: {}", e.getMessage(), e);
}
}
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);
}
//设备在线状态
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei()+ DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
if(StringUtils.isNotBlank(onlineStatus)){
vo.setOnlineStatus(1);
}else{
vo.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);
vo.setMainLightMode(jsonObject.getString("mainLightMode"));
vo.setLaserLightMode(jsonObject.getString("laserLightMode"));
vo.setBatteryPercentage(jsonObject.getString("batteryPercentage"));
vo.setChargeState(jsonObject.getString("chargeState"));
vo.setBatteryRemainingTime(jsonObject.getString("batteryRemainingTime"));
}else{
vo.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);
vo.setLongitude(jsonObject.get("longitude").toString());
vo.setLatitude(jsonObject.get("latitude").toString());
vo.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)){
vo.setAlarmStatus(alarmStatus);
}
String lightBrightness = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ device.getDeviceImei()+ DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
if(StringUtils.isNotBlank(lightBrightness)){
vo.setLightBrightness(lightBrightness);
}
return vo;
}
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
Long deviceId = bo.getDeviceId();
Device deviceObj = deviceMapper.selectById(deviceId);
if (deviceObj == null) {
throw new RuntimeException("请先将设备入库!!!");
}
if(getDeviceStatus(deviceObj.getDeviceImei())){
throw new ServiceException(deviceObj.getDeviceName()+",设备已断开连接");
}
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
.eq("device_id", deviceId);
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
// unitName,position,name,id
byte[] unitName = generateFixedBitmapData(bo.getUnitName(), 120);
byte[] position = generateFixedBitmapData(bo.getPosition(), 120);
byte[] name = generateFixedBitmapData(bo.getName(), 120);
byte[] id = generateFixedBitmapData(bo.getCode(), 120);
ArrayList<Integer> intData = new ArrayList<>();
intData.add(2);
buildArr(convertHexToDecimal(unitName), intData);
buildArr(convertHexToDecimal(position), intData);
buildArr(convertHexToDecimal(name), intData);
buildArr(convertHexToDecimal(id), 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 + deviceObj.getDeviceImei(), 1, JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), bo);
recordDeviceLog(deviceId, deviceObj.getDeviceName(), "人员信息登记", JSON.toJSONString(bo), AppLoginHelper.getUserId());
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;
}
}
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
try {
Device device = deviceMapper.selectById(bo.getDeviceId());
if (device == null) {
throw new ServiceException("设备不存在");
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
MultipartFile file = bo.getFile();
byte[] largeData = ImageToCArrayConverter.convertImageToCArray(file.getInputStream(), 160, 80, 25600);
log.info("长度:" + largeData.length);
log.info("原始数据大小: {} 字节", largeData.length);
int[] ints = convertHexToDecimal(largeData);
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() +DEVICE_BOOT_LOGO_KEY_PREFIX, Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX);
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
log.info("第0块数据大小: {} 字节", specificChunk.length);
// log.info("第0块数据: {}", Arrays.toString(specificChunk));
ArrayList<Integer> intData = new ArrayList<>();
intData.add(3);
intData.add(1);
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", "上传开机画面", AppLoginHelper.getUserId());
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送指令失败");
}
}
/**
* 灯光模式
* 0关灯1强光模式2弱光模式, 3爆闪模式, 4泛光模式
*/
public void lightModeSettings(DeviceInstructDto params) {
try {
Long deviceId = params.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if(device == null){
throw new ServiceException("设备不存在");
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
Integer instructValue = Integer.parseInt(params.getInstructValue());
ArrayList<Integer> intData = new ArrayList<>();
intData.add(1);
intData.add(instructValue);
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
LightModeEnum modeEnum = LightModeEnum.getByCode(instructValue);
recordDeviceLog(device.getId(), device.getDeviceName(), "灯光模式", modeEnum!=null?modeEnum.getName():null, AppLoginHelper.getUserId());
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送指令失败");
}
}
//灯光亮度设置
public void lightBrightnessSettings(DeviceInstructDto params) {
try {
Long deviceId = params.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if(device == null){
throw new ServiceException("设备不存在");
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
String instructValue = params.getInstructValue();
ArrayList<Integer> intData = new ArrayList<>();
intData.add(5);
String[] values = instructValue.split("\\.");
String value1 = values[0];
String value2 = values[1];
if(StringUtils.isNoneBlank(value1)){
intData.add(Integer.parseInt(value1));
}
if(StringUtils.isNoneBlank(value2)){
intData.add(Integer.parseInt(value2));
}
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送指令失败");
}
}
//激光模式设置
public void laserModeSettings(DeviceInstructDto params) {
try {
Long deviceId = params.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if(device == null){
throw new ServiceException("设备不存在");
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
Integer instructValue = Integer.parseInt(params.getInstructValue());
ArrayList<Integer> intData = new ArrayList<>();
intData.add(4);
intData.add(instructValue);
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
// 1代表开启激光灯此时主灯关闭主灯控件为关机状态为0代表关闭激光灯
if("1".equals(params.getInstructValue())){
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "开启激光灯", AppLoginHelper.getUserId());
}else{
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "关闭激光灯", AppLoginHelper.getUserId());
}
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送指令失败");
}
}
public String mapReverseGeocoding(DeviceInstructDto params) {
QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("device_imei", params.getDeviceImei());
List<Device> devices = deviceMapper.selectList(queryWrapper);
if(ObjectUtils.length( devices) ==0){
throw new ServiceException("设备不存在");
}
return RedisUtils.getCacheObject("device:location:" + devices.get(0).getDeviceImei());
}
public int sendAlarmMessage(AppDeviceSendMsgBo bo) {
try {
List<Long> deviceIds = bo.getDeviceIds();
if (deviceIds == null || deviceIds.isEmpty()) {
throw new ServiceException("请选择设备");
}
for (Long deviceId : deviceIds) {
Device device = deviceMapper.selectById(deviceId);
if (device == null) {
throw new ServiceException("设备不存在" + deviceId);
}
if(getDeviceStatus(device.getDeviceImei())){
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
}
try {
ArrayList<Integer> intData = new ArrayList<>();
intData.add(7);
intData.add(Integer.parseInt(bo.getInstructValue()));
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+device.getDeviceImei(), 1 , JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),JSON.toJSONString(map));
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", deviceId)
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("send_msg", bo.getSendMsg());
deviceMapper.update(updateWrapper);
recordDeviceLog(device.getId(), device.getDeviceName(), "发送告警信息", bo.getSendMsg(), AppLoginHelper.getUserId());
} catch (Exception e) {
log.info("设备发送告警信息信息失败:{}" ,deviceId);
throw new ServiceException("设备发送告警信息信息失败");
}
}
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送告警信息指令失败");
}
return 1;
}
private boolean getDeviceStatus(String deviceImei) {
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
return StringUtils.isBlank(deviceOnlineStatusRedisKey);
}
}

View File

@ -0,0 +1,293 @@
package com.fuyuanshen.web.service.device;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
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.AppDeviceBindRecord;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.ObjectUtils;
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.dto.AppDeviceBo;
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.DeviceLogMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.web.service.device.status.base.DeviceStatusRule;
import com.fuyuanshen.web.service.device.status.base.RealTimeStatusEngine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceBizService {
private final APPDeviceMapper appDeviceMapper;
private final DeviceMapper deviceMapper;
private final AppDeviceBindRecordMapper appDeviceBindRecordMapper;
private final RealTimeStatusEngine realTimeStatusEngine;
private final DeviceLogMapper deviceLogMapper;
private final AppDeviceShareMapper appDeviceShareMapper;
private final AppUserMapper appUserMapper;;
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 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);
List<AppDeviceVo> records = result.getRecords();
if(records != null && !records.isEmpty()){
records.forEach(item -> {
if(item.getCommunicationMode()!=null && item.getCommunicationMode() == 0){
//设备在线状态
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
if(StringUtils.isNotBlank(onlineStatus)){
item.setOnlineStatus(1);
}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);
}
}
});
}
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("设备已绑定");
}
QueryWrapper<AppDeviceBindRecord> bindRecordQueryWrapper = new QueryWrapper<>();
bindRecordQueryWrapper.eq("device_id", device.getId());
AppDeviceBindRecord appDeviceBindRecord = appDeviceBindRecordMapper.selectOne(bindRecordQueryWrapper);
if (appDeviceBindRecord != null) {
UpdateWrapper<AppDeviceBindRecord> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("device_id", device.getId())
.set("binding_status", BindingStatusEnum.BOUND.getCode())
.set("binding_user_id", userId)
.set("update_time", new Date())
.set("binding_time", new Date());
return appDeviceBindRecordMapper.update(null, deviceUpdateWrapper);
} else {
AppDeviceBindRecord bindRecord = new AppDeviceBindRecord();
bindRecord.setDeviceId(device.getId());
bindRecord.setBindingUserId(userId);
bindRecord.setBindingTime(new Date());
bindRecord.setCreateBy(userId);
appDeviceBindRecordMapper.insert(bindRecord);
}
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);
QueryWrapper<AppDeviceBindRecord> bindRecordQueryWrapper = new QueryWrapper<>();
bindRecordQueryWrapper.eq("device_id", device.getId());
bindRecordQueryWrapper.eq("binding_user_id", userId);
AppDeviceBindRecord appDeviceBindRecord = appDeviceBindRecordMapper.selectOne(bindRecordQueryWrapper);
if (appDeviceBindRecord != null) {
UpdateWrapper<AppDeviceBindRecord> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("device_id", device.getId())
.eq("binding_user_id", userId)
.set("binding_user_id", userId)
.set("binding_time", new Date());
return appDeviceBindRecordMapper.update(null, deviceUpdateWrapper);
} else {
AppDeviceBindRecord bindRecord = new AppDeviceBindRecord();
bindRecord.setDeviceId(device.getId());
bindRecord.setBindingUserId(userId);
bindRecord.setBindingTime(new Date());
bindRecord.setCreateBy(userId);
appDeviceBindRecordMapper.insert(bindRecord);
}
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) {
return unBindDevice(id, null, 1);
}
public int unBindDevice(Long id, Long userId, int type) {
Device device = deviceMapper.selectById(id);
if (device == null) {
throw new RuntimeException("请先将设备入库!!!");
}
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", device.getId())
.set("binding_user_id", null)
.set("binding_status", BindingStatusEnum.UNBOUND.getCode())
.set("binding_time", null);
deviceMapper.update(null, deviceUpdateWrapper);
if (userId == null) {
userId = AppLoginHelper.getUserId();
}
QueryWrapper<AppDeviceBindRecord> bindRecordQueryWrapper = new QueryWrapper<>();
bindRecordQueryWrapper.eq("device_id", device.getId());
// 设备端解绑 0:设备端解绑 1:web端解绑
if (type == 1) {
bindRecordQueryWrapper.eq("binding_user_id", userId);
}
// AppDeviceBindRecord appDeviceBindRecord = appDeviceBindRecordMapper.selectOne(bindRecordQueryWrapper);
// if (appDeviceBindRecord != null) {
// return appDeviceBindRecordMapper.deleteById(appDeviceBindRecord.getId());
// }
List<AppDeviceBindRecord> appDeviceBindRecordList = appDeviceBindRecordMapper.selectList(bindRecordQueryWrapper);
if (CollectionUtil.isNotEmpty(appDeviceBindRecordList)) {
appDeviceBindRecordList.forEach(appDeviceBindRecord ->
appDeviceBindRecordMapper.deleteById(appDeviceBindRecord.getId()));
}
AppUserVo appUserVo = appUserMapper.selectVoById(userId);
QueryWrapper<AppDeviceShare> appDeviceShareQueryWrapper = new QueryWrapper<>();
appDeviceShareQueryWrapper.eq("device_id", device.getId());
appDeviceShareQueryWrapper.eq("phonenumber", appUserVo.getPhonenumber());
List<AppDeviceShare> appDeviceShareList = appDeviceShareMapper.selectList(appDeviceShareQueryWrapper);
if (CollectionUtil.isNotEmpty(appDeviceShareList)) {
appDeviceShareList.forEach(appDeviceShare ->
appDeviceShareMapper.deleteById(appDeviceShare.getId()));
}
return 1;
}
public String mapReverseGeocoding(DeviceInstructDto params) {
// Long deviceId = params.getDeviceId();
// Device device = deviceMapper.selectById(deviceId);
QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("device_imei", params.getDeviceImei());
List<Device> devices = deviceMapper.selectList(queryWrapper);
if(ObjectUtils.length( devices) ==0){
throw new ServiceException("设备不存在");
}
return RedisUtils.getCacheObject("device:location:" + devices.get(0).getDeviceImei());
}
public Map<String, Object> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
try {
String commandType = statusDto.getTypeName()+"_" + statusDto.getFunctionMode();
DeviceStatusRule rule = realTimeStatusEngine.getDeviceStatusRule(commandType);
if(rule == null){
throw new ServiceException("未匹配到处理命令");
}
return rule.getStatus(statusDto);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
public AppDeviceVo getDeviceInfo(String deviceMac) {
// QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
// queryWrapper.eq("device_mac", deviceMac);
// List<Device> devices = deviceMapper.selectList(queryWrapper);
return deviceMapper.getDeviceInfo(deviceMac);
}
}

View File

@ -0,0 +1,75 @@
package com.fuyuanshen.web.service.device.status;
import cn.hutool.json.JSONUtil;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import com.fuyuanshen.web.service.device.status.base.DeviceStatusRule;
import com.fuyuanshen.web.service.device.status.constants.DeviceTypeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
@Slf4j
@Component
public class FunctionAccessBatchStatusRule implements DeviceStatusRule {
@Override
public String getCommandType() {
return DeviceTypeConstants.TYPE_BJQ6170+"_2";
}
@Override
public boolean supports(String deviceType) {
return true; // 适用于所有设备类型
}
@Override
public Map<String, Object> getStatus(AppRealTimeStatusDto dto) {
Map<String, Object> status = new HashMap<>();
String functionAccess = RedisUtils.getCacheObject(
FUNCTION_ACCESS_KEY + dto.getBatchId());
log.info("FunctionAccessBatchStatusRule:{}",functionAccess);
if(StringUtils.isBlank(functionAccess)){
status.put("functionAccess", FunctionAccessStatus.OK.getCode());
return status;
}
List<String> cachedDeviceImeiList = JSONUtil.toList(functionAccess, String.class);
if(cachedDeviceImeiList.isEmpty()){
status.put("functionAccess", FunctionAccessStatus.OK.getCode());
return status;
}
for (String key : cachedDeviceImeiList) {
String item = RedisUtils.getCacheObject(FUNCTION_ACCESS_KEY + key);
if("ACTIVE".equals(item)){
status.put("functionAccess", FunctionAccessStatus.ACTIVE.getCode());
break;
}else {
status.put("functionAccess", FunctionAccessStatus.OK.getCode());
}
// if (StringUtils.isBlank(item)) {
// String timeOut = RedisUtils.getCacheObject(FUNCTION_ACCESS_TIMEOUT_KEY + dto.getDeviceImei());
// if ("TIMEOUT".equals(timeOut)) {
// status.put("functionAccess", FunctionAccessStatus.TIMEOUT.getCode());
// break;
// } else {
// status.put("functionAccess", FunctionAccessStatus.OK.getCode());
// }
// } else {
// if (!FunctionAccessStatus.OK.getCode().equals(item)) {
// status.put("functionAccess", FunctionAccessStatus.FAILED.getCode());
// break;
// } else {
// status.put("functionAccess", FunctionAccessStatus.OK.getCode());
// }
// }
}
return status;
}
}

View File

@ -0,0 +1,51 @@
package com.fuyuanshen.web.service.device.status;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import com.fuyuanshen.web.service.device.status.base.DeviceStatusRule;
import com.fuyuanshen.web.service.device.status.constants.DeviceTypeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
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.FUNCTION_ACCESS_TIMEOUT_KEY;
// 上传开机图片
@Slf4j
@Component
public class FunctionAccessStatusRule implements DeviceStatusRule {
@Override
public String getCommandType() {
return DeviceTypeConstants.TYPE_BJQ6170+"_1";
}
@Override
public boolean supports(String deviceType) {
return true; // 适用于所有设备类型
}
@Override
public Map<String, Object> getStatus(AppRealTimeStatusDto dto) {
Map<String, Object> status = new HashMap<>();
String functionAccess = RedisUtils.getCacheObject(
FUNCTION_ACCESS_KEY + dto.getDeviceImei());
log.info("FunctionAccessStatusRule:{}",functionAccess);
if(StringUtils.isBlank(functionAccess)){
String timeOut = RedisUtils.getCacheObject(FUNCTION_ACCESS_TIMEOUT_KEY + dto.getDeviceImei());
if("TIMEOUT".equals(timeOut)){
status.put("functionAccess", FunctionAccessStatus.TIMEOUT.getCode());
RedisUtils.deleteObject(FUNCTION_ACCESS_TIMEOUT_KEY + dto.getDeviceImei());
}else{
status.put("functionAccess", FunctionAccessStatus.OK.getCode());
}
}else{
status.put("functionAccess", functionAccess);
}
return status;
}
}

View File

@ -0,0 +1,19 @@
package com.fuyuanshen.web.service.device.status.base;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import java.util.Map;
// 规则接口
public interface DeviceStatusRule {
/**
* 获取命令类型
* @return 命令类型
*/
String getCommandType();
boolean supports(String deviceType);
Map<String, Object> getStatus(AppRealTimeStatusDto statusDto);
}

View File

@ -0,0 +1,23 @@
package com.fuyuanshen.web.service.device.status.base;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.List;
@Component
public class RealTimeStatusEngine {
private final LinkedHashMap<String, DeviceStatusRule> rulesMap = new LinkedHashMap<>();
public RealTimeStatusEngine(List<DeviceStatusRule> rules) {
rules.forEach(rule -> rulesMap.put(rule.getCommandType(), rule)
);
}
public DeviceStatusRule getDeviceStatusRule(String commandType) {
return rulesMap.get(commandType);
}
}

View File

@ -0,0 +1,6 @@
package com.fuyuanshen.web.service.device.status.constants;
public class DeviceTypeConstants {
public static final String TYPE_BJQ6170 = "BJQ6170";
}

View File

@ -0,0 +1,125 @@
package com.fuyuanshen.web.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fuyuanshen.app.domain.AppUser;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.app.service.AppLoginService;
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.model.AppLoginUser;
import com.fuyuanshen.common.core.domain.model.PasswordLoginBody;
import com.fuyuanshen.common.core.enums.LoginType;
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.StringUtils;
import com.fuyuanshen.common.core.utils.ValidatorUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.common.web.config.properties.CaptchaProperties;
import com.fuyuanshen.system.domain.vo.SysClientVo;
import com.fuyuanshen.web.domain.vo.LoginVo;
import com.fuyuanshen.web.service.IAuthStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* 密码认证策略
*
* @author Michelle.Chung
*/
@Slf4j
@Service("appPassword" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppPasswordAuthStrategy implements IAuthStrategy {
private final CaptchaProperties captchaProperties;
private final AppLoginService loginService;
private final AppUserMapper appUserMapper;
@Override
public LoginVo login(String body, SysClientVo client) {
PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
ValidatorUtils.validate(loginBody);
String tenantId = loginBody.getTenantId();
String username = loginBody.getUsername();
String password = loginBody.getPassword();
String code = loginBody.getCode();
String uuid = loginBody.getUuid();
// boolean captchaEnabled = captchaProperties.getEnable();
// // 验证码开关
// if (captchaEnabled) {
// validateCaptcha(tenantId, username, code, uuid);
// }
AppLoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
AppUserVo user = loadUserByUsername(username);
loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !password.equals(user.getPassword()));
// 此处可根据登录用户的数据不同 自行创建 loginUser
return loginService.buildLoginUser(user);
});
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = new SaLoginParameter();
model.setDeviceType(client.getDeviceType());
// 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
// 例如: 后台用户30分钟过期 app用户1天过期
model.setTimeout(client.getTimeout());
model.setActiveTimeout(client.getActiveTimeout());
model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
// 生成token
AppLoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
private void validateCaptcha(String tenantId, String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha)) {
loginService.recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
private AppUserVo loadUserByUsername(String username) {
AppUserVo user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getUserName, username)
.eq(AppUser::getUserType, UserType.APP_USER.getUserType()));
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", username);
throw new UserException("user.not.exists", username);
} else if (SystemConstants.DISABLE.equals(user.getStatus())) {
log.info("登录用户:{} 已被停用.", username);
throw new UserException("user.blocked", username);
}
return user;
}
}

View File

@ -14,12 +14,10 @@ import com.fuyuanshen.common.core.constant.SystemConstants;
import com.fuyuanshen.common.core.domain.model.AppLoginUser;
import com.fuyuanshen.common.core.domain.model.SmsLoginBody;
import com.fuyuanshen.common.core.enums.LoginType;
import com.fuyuanshen.common.core.enums.UserType;
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.StringUtils;
import com.fuyuanshen.common.core.utils.ValidatorUtils;
import com.fuyuanshen.common.core.utils.*;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
@ -60,9 +58,10 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
AppUserVo user = loadUserByPhonenumber(phonenumber);
if (ObjectUtil.isNull(user)) {
//新增Appuser
addAppUser(tenantId, phonenumber);
user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getPhonenumber, phonenumber));
AppUser appUser = addAppUser(tenantId, phonenumber);
user = new AppUserVo();
MapstructUtils.convert(appUser, user);
// user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getPhonenumber, phonenumber));
// loginService.recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists", phonenumber));
// throw new UserException("user.not.exists", phonenumber);
}
@ -72,6 +71,7 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
});
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
loginUser.setUserType(UserType.APP_USER.getUserType());
SaLoginParameter model = new SaLoginParameter();
model.setDeviceType(client.getDeviceType());
// 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
@ -89,7 +89,7 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
return loginVo;
}
private void addAppUser(String tenantId, String phonenumber) {
private AppUser addAppUser(String tenantId, String phonenumber) {
AppUser appUser = new AppUser();
appUser.setPhonenumber(phonenumber);
appUser.setUserName(phonenumber);
@ -98,6 +98,7 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
appUser.setLoginIp(ServletUtils.getClientIP());
appUser.setTenantId(tenantId);
appUserMapper.insert(appUser);
return appUser;
}
@ -114,7 +115,9 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
}
private AppUserVo loadUserByPhonenumber(String phonenumber) {
AppUserVo user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getPhonenumber, phonenumber));
AppUserVo user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getPhonenumber, phonenumber)
.eq(AppUser::getUserType, UserType.APP_USER.getUserType()));
if (ObjectUtil.isNull(user)) {
log.info("登录用户:{} 不存在.", phonenumber);
// throw new UserException("user.not.exists", phonenumber);
@ -126,5 +129,4 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
}
return user;
}
}

View File

@ -0,0 +1,73 @@
package com.fuyuanshen.web.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.web.service.WEBDeviceService;
import com.fuyuanshen.web.service.device.DeviceBizService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Description:
* @Author: WY
* @Date: 2025/5/16
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class WEBDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements WEBDeviceService {
private final DeviceBizService appDeviceService;
private final DeviceAssignmentsMapper deviceAssignmentsMapper;
private final AppDeviceBindRecordMapper appDeviceBindRecordMapper;
private final DeviceMapper deviceMapper;
/**
* WEB端解绑设备
*
* @param id
* @return
*/
@Override
@Transactional
public int webUnBindDevice(Long id, Long userId) {
// 设备端解绑 0:设备端解绑 1:web端解绑
int type = 1;
if (userId == null) {
DeviceAssignments deviceAssignments = deviceAssignmentsMapper.selectById(id);
if (deviceAssignments == null) {
throw new RuntimeException("请先将设备入库!!!");
}
id = deviceAssignments.getDeviceId();
type = 0;
}
QueryWrapper<AppDeviceBindRecord> deviceId = new QueryWrapper<AppDeviceBindRecord>().eq("device_id", id);
// appDeviceService.unBindDevice(id, userId, type);
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
deviceUpdateWrapper.eq("id", id)
.set("binding_user_id", null)
.set("binding_status", BindingStatusEnum.UNBOUND.getCode())
.set("binding_time", null);
deviceMapper.update(null, deviceUpdateWrapper);
return appDeviceBindRecordMapper.delete(deviceId);
}
}

View File

@ -8,8 +8,8 @@ spring.boot.admin.client:
metadata:
username: ${spring.boot.admin.client.username}
userpassword: ${spring.boot.admin.client.password}
username: @monitor.username@
password: @monitor.password@
username: ${monitor.username}
password: ${monitor.password}
--- # snail-job 配置
snail-job:
@ -49,9 +49,9 @@ spring:
driverClassName: com.mysql.cj.jdbc.Driver
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: jdbc:mysql://47.120.79.150:3306/fys-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
url: jdbc:mysql://120.79.224.186:3366/fys-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: root
password: Jq_123456#
password: 1fys@QWER..
# # 从库数据源
# slave:
# lazy: true
@ -98,13 +98,13 @@ spring:
spring.data:
redis:
# 地址
host: 47.120.79.150
host: 120.79.224.186
# 端口默认为6379
port: 6379
port: 26379
# 数据库索引
database: 2
# redis 密码必须配置
password: xhYc_djkl382^#780!
password: 1fys@QWER..
# 连接超时时间
timeout: 10s
# 是否开启ssl
@ -174,14 +174,14 @@ sms:
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
supplier: alibaba
# 有些称为accessKey有些称之为apiKey也有称为sdkKey或者appId。
access-key-id: LTAI5tJdDNpZootsPQ5hdELx
access-key-id: LTAI5tDGfJd4kMvrGtvyzCHz
# 称为accessSecret有些称之为apiSecret
access-key-secret: mU4WtffcCXpHPz5tLwQpaGtLsJXONt
access-key-secret: a4ZlVHVSYeMQHn0p1R18thA6xCdHQh
#模板ID 非必须配置如果使用sendMessage的快速发送需此配置
template-id: SMS_322180518
template-id: SMS_324526343
#模板变量 上述模板的变量
templateName: code
signature: 湖北星汉研创科技
signature: 深圳市富源晟科技
# sdk-app-id: 您的sdkAppId
config2:
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
@ -300,9 +300,9 @@ file:
# MQTT配置
mqtt:
username: admin
password: #YtvpSfCNG
url: tcp://47.120.79.150:2883
password: fys123456
url: tcp://47.107.152.87:1883
subClientId: fys_subClient
subTopic: worker/alert/#,worker/location/#
pubTopic: worker/location
subTopic: worker/location/#
pubTopic: B/#
pubClientId: fys_pubClient

View File

@ -4,7 +4,7 @@ spring.servlet.multipart.location: /fys/server/temp
--- # 监控中心配置
spring.boot.admin.client:
# 增加客户端开关
enabled: true
enabled: false
url: http://localhost:9090/admin
instance:
service-host-type: IP
@ -16,7 +16,7 @@ spring.boot.admin.client:
--- # snail-job 配置
snail-job:
enabled: true
enabled: false
# 需要在 SnailJob 后台组管理创建对应名称的组,然后创建任务的时候选择对应的组,才能正确分派任务
group: "fys_group"
# SnailJob 接入验证令牌 详见 script/sql/ry_job.sql `sj_group_config`表
@ -52,7 +52,7 @@ spring:
driverClassName: com.mysql.cj.jdbc.Driver
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: jdbc:mysql://localhost:3306/fys_vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
url: jdbc:mysql://47.107.152.87:3306/fys-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
username: root
password: Jz_5623_cl1
# # 从库数据源
@ -101,7 +101,7 @@ spring:
spring.data:
redis:
# 地址
host: localhost
host: 47.107.152.87
# 端口默认为6379
port: 6379
# 数据库索引
@ -177,11 +177,14 @@ sms:
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
supplier: alibaba
# 有些称为accessKey有些称之为apiKey也有称为sdkKey或者appId。
access-key-id: 您的accessKey
access-key-id: LTAI5tDGfJd4kMvrGtvyzCHz
# 称为accessSecret有些称之为apiSecret
access-key-secret: 您的accessKeySecret
signature: 您的短信签名
sdk-app-id: 您的sdkAppId
access-key-secret: a4ZlVHVSYeMQHn0p1R18thA6xCdHQh
#模板ID 非必须配置如果使用sendMessage的快速发送需此配置
template-id: SMS_324526343
#模板变量 上述模板的变量
templateName: code
signature: 深圳市富源晟科技
config2:
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
supplier: tencent
@ -277,12 +280,13 @@ justauth:
# MQTT配置
mqtt:
username: admin
password: #YtvpSfCNG
url: tcp://47.120.79.150:2883
password: fys123456
url: tcp://47.107.152.87:1883
subClientId: fys_subClient
subTopic: worker/alert/#,worker/location/#
pubTopic: worker/location
subTopic: A/#,worker/location/#
pubTopic: B/#
pubClientId: fys_pubClient
enabled: false
# 文件存储路径

View File

@ -1,7 +1,7 @@
# 开发环境配置
server:
# 服务器的HTTP端口默认为8080
port: 8000
port: 8001
servlet:
# 应用的访问路径
context-path: /
@ -35,7 +35,8 @@ captcha:
# 日志配置
logging:
level:
com.fuyuanshen: @logging.level@
#com.fuyuanshen: @logging.level@
com.fuyuanshen: ${logging.level}
org.springframework: warn
org.mybatis.spring.mapper: error
org.apache.fury: warn
@ -63,7 +64,7 @@ spring:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: @profiles.active@
active: ${profiles.active}
# 文件上传
servlet:
multipart:
@ -231,7 +232,7 @@ xss:
# 如使用JDK21请直接使用虚拟线程 不要开启此配置
thread-pool:
# 是否开启线程池
enabled: false
enabled: true
# 队列最大长度
queueCapacity: 128
# 线程池维护线程所允许的空闲时间
@ -254,7 +255,7 @@ management:
health:
show-details: ALWAYS
logfile:
external-file: ./logs/sys-console.log
external-file: ./logs/sys-admin-console.log
--- # 默认/推荐使用sse推送
sse:

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

View File

@ -15,13 +15,13 @@
<!-- 控制台输出 -->
<appender name="file_console" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-console.log</file>
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> -->
<!-- &lt;!&ndash; 日志文件名格式 &ndash;&gt; -->
<!-- <fileNamePattern>${log.path}/sys-console.%d{yyyy-MM-dd}.log</fileNamePattern> -->
<!-- &lt;!&ndash; 日志最大 1天 &ndash;&gt; -->
<!-- <maxHistory>1</maxHistory> -->
<!-- </rollingPolicy> -->
<file>${log.path}/sys-admin-console.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-admin-console.log.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大 1天 -->
<maxHistory>1</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>utf-8</charset>

View File

@ -17,6 +17,16 @@ public interface GlobalConstants {
*/
String CAPTCHA_CODE_KEY = GLOBAL_REDIS_KEY + "captcha_codes:";
/**
* 设备分享验证码 redis key
*/
String DEVICE_SHARE_CODES_KEY = GLOBAL_REDIS_KEY + "device_share_codes:";
/**
* 验证码 redis key
*/
String APP_FORGOT_PASSWORD_SMS_KEY = GLOBAL_REDIS_KEY + "app_sms_forgotPassword:";
/**
* 防重提交 redis key
*/
@ -31,4 +41,9 @@ public interface GlobalConstants {
* 三方认证 redis key
*/
String SOCIAL_AUTH_CODE_KEY = GLOBAL_REDIS_KEY + "social_auth_codes:";
String FUNCTION_ACCESS_KEY = GLOBAL_REDIS_KEY + "device:function_access:";
String FUNCTION_ACCESS_TIMEOUT_KEY = GLOBAL_REDIS_KEY + "device:function_access_timeout:";
}

View File

@ -0,0 +1,22 @@
package com.fuyuanshen.common.core.domain.model;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class AppLoginBody {
/**
* 手机号不能为空
*/
@NotBlank(message = "手机号不能为空")
private String userName;
/**
* 密码不能为空
*/
@NotBlank(message = "密码不能为空")
private String password;
private String tenantId;
}

View File

@ -0,0 +1,22 @@
package com.fuyuanshen.common.core.domain.model;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
@Data
public class AppSmsRegisterBody {
@NotBlank(message = "手机号不能为空")
private String phoneNumber;
@NotBlank(message = "密码不能为空")
private String password;
@NotBlank(message = "验证码不能为空")
private String verificationCode;
/**
* 租户ID
*/
private String tenantId;
}

View File

@ -18,14 +18,14 @@ public class PasswordLoginBody extends LoginBody {
* 用户名
*/
@NotBlank(message = "{user.username.not.blank}")
@Length(min = 2, max = 30, message = "{user.username.length.valid}")
// @Length(min = 2, max = 30, message = "{user.username.length.valid}")
private String username;
/**
* 用户密码
*/
@NotBlank(message = "{user.password.not.blank}")
@Length(min = 5, max = 30, message = "{user.password.length.valid}")
// @Length(min = 5, max = 30, message = "{user.password.length.valid}")
private String password;
}

View File

@ -21,7 +21,13 @@ public enum UserType {
/**
* 移动客户端用户
*/
APP_USER("app_user");
APP_USER("app_user"),
/**
* 小程序 用户
*/
XCX_USER("xcx_user");
/**
* 用户类型标识(用于 token、权限识别等

View File

@ -0,0 +1,362 @@
package com.fuyuanshen.common.core.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 80*12像素点阵生成工具
*/
public class Bitmap80x12Generator {
public static void main(String[] args) throws IOException {
// 测试生成中文文本的点阵数据
String text = "张三";
byte[] bitmapData = generateFixedBitmapData(text, 120);
// System.out.println(Arrays.toString(bitmapData));
int[] ints = convertHexToDecimal(bitmapData);
System.out.println(Arrays.toString(ints));
// 生成预览图片
byte[] bytes = convertDecimalToByteArray(ints);
BufferedImage image = convertByteArrayToImage(bytes, 12, 80);
ImageIO.write(image, "PNG", new File("D:\\bitmap_preview.png"));
System.out.println("成功生成预览图片: D:\\bitmap_preview.png");
// 打印十六进制数据
// System.out.println("生成的点阵数据2:");
// printHexData(bitmapData);
// int[] ints = convertHexToDecimal(bitmapData);
System.out.println("打印十进制无符号:"+Arrays.toString(ints));
// printDecimalData(bitmapData);
// 生成C文件
generateCFile(bitmapData, "bitmap_data.c", "chinese_text");
}
/**
* 将十进制整数数组转换为字节数组
*
* @param decimalArray 十进制整数数组假设每个值都在0-255范围内
* @return 字节数组
*/
public static byte[] convertDecimalToByteArray(int[] decimalArray) {
if (decimalArray == null) {
return new byte[0];
}
byte[] byteArray = new byte[decimalArray.length];
for (int i = 0; i < decimalArray.length; i++) {
// 确保值在0-255范围内这是byte的无符号表示范围
int value = decimalArray[i] & 0xFF;
byteArray[i] = (byte) value;
}
return byteArray;
}
/**
* 打印字节数组(以十进制形式显示)
*
* @param data 字节数组
*/
public static void printByteArrayAsDecimal(byte[] data) {
System.out.println("字节数组(十进制显示):");
for (int i = 0; i < data.length; i++) {
// 将字节转换为无符号十进制数显示
int value = data[i] & 0xFF;
System.out.print(value);
if (i < data.length - 1) {
System.out.print(", ");
if ((i + 1) % 12 == 0) {
System.out.println();
}
}
}
System.out.println();
}
/**
* 将十六进制字节数组转换为十进制整数数组
*
* @param data 字节数组
* @return 十进制整数数组
*/
public static int[] convertHexToDecimal(byte[] data) {
if (data == null) {
return new int[0];
}
int[] decimalArray = new int[data.length];
for (int i = 0; i < data.length; i++) {
// 将字节转换为无符号整数(十进制)
decimalArray[i] = data[i] & 0xFF;
}
return decimalArray;
}
/**
* 打印十进制数据
*
* @param data 字节数组
*/
public static void printDecimalData(byte[] data) {
int[] decimalArray = convertHexToDecimal(data);
System.out.println("生成的十进制数据:");
for (int i = 0; i < decimalArray.length; i++) {
System.out.print(decimalArray[i]);
if (i < decimalArray.length - 1) {
System.out.print(", ");
if ((i + 1) % 12 == 0) {
System.out.println();
}
}
}
System.out.println();
}
public static void buildArr(int[] data,List<Integer> intData){
for (int datum : data) {
intData.add(datum);
}
}
/**
* 生成固定长度的点阵数据
*
* @param text 要转换的文本
* @param fixedLength 固定长度(字节)
* @return 固定长度的点阵数据
*/
public static byte[] generateFixedBitmapData(String text, int fixedLength) {
if (text == null || text.isEmpty()) {
return new byte[fixedLength];
}
// 创建80*12像素的图像
Font font = new Font("宋体", Font.PLAIN, 12);
BufferedImage image = createTextImage(text, font, 80, 12);
// 提取点阵数据
byte[] rawData = extractBitmapData(image);
// System.out.println("生成的点阵数据1:");
// System.out.println(Arrays.toString(rawData));
// 调整到固定长度
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
// 剩余部分自动初始化为0
return result;
}
/**
* 创建文本图像
*/
private static BufferedImage createTextImage(String text, Font font, int width, int height) {
// 创建图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 设置白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 设置黑色文本
g.setColor(Color.BLACK);
g.setFont(font);
// 关闭抗锯齿
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
// 获取字体度量
FontMetrics metrics = g.getFontMetrics();
// 计算文本绘制位置(居中)
int textWidth = metrics.stringWidth(text);
// int x = Math.max(0, (width - textWidth) / 2); // 水平居中
// 左对齐
int x = 0;
int y = (height - metrics.getHeight()) / 2 + metrics.getAscent(); // 垂直居中
// 绘制文本
g.drawString(text, x, y);
g.dispose();
return image;
}
/**
* 提取点阵数据 - 从左到右,从上到下扫描
*/
private static byte[] extractBitmapData(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
List<Byte> byteList = new ArrayList<>();
int currentByte = 0;
int bitCount = 0;
// 从上到下,从左到右扫描
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// 获取像素颜色
Color color = new Color(image.getRGB(x, y));
// 判断是否为黑色(阈值处理)
int gray = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
boolean isBlack = gray < 128;
// 高位优先打包
currentByte = (currentByte << 1) | (isBlack ? 1 : 0);
bitCount++;
if (bitCount == 8) {
byteList.add((byte) currentByte);
currentByte = 0;
bitCount = 0;
}
}
}
// 处理最后不满8位的部分
if (bitCount > 0) {
currentByte <<= (8 - bitCount);
byteList.add((byte) currentByte);
}
return byteListToArray(byteList);
}
public static byte[] byteListToArray(List<Byte> byteList) {
byte[] result = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
result[i] = byteList.get(i);
}
return result;
}
/**
* 字节数组转图像
*/
public static BufferedImage convertByteArrayToImage(byte[] data, int height, int width) {
if (data == null || data.length == 0) {
return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}
// 创建RGB图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 设置白色背景
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
image.setRGB(x, y, Color.WHITE.getRGB());
}
}
// 从左到右,从上到下设置像素点
int bitIndex = 0;
for (int i = 0; i < data.length; i++) {
int value = data[i] & 0xFF;
for (int bit = 7; bit >= 0; bit--) { // 高位在前
boolean isBlack = ((value >> bit) & 1) == 1;
if (isBlack) {
int x = bitIndex % width;
int y = bitIndex / width;
if (x < width && y < height) { // 确保不越界
image.setRGB(x, y, Color.BLACK.getRGB());
}
}
bitIndex++;
// 如果已经处理完所有像素,则退出
if (bitIndex >= width * height) {
return image;
}
}
}
return image;
}
public static String convertToCArrayString(byte[] data, String arrayName) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("// %s: %d 字节\n", arrayName, data.length));
sb.append(String.format("const uint8_t %s[] = {\n ", arrayName));
for (int i = 0; i < data.length; i++) {
sb.append(String.format("0x%02X", data[i] & 0xFF));
if (i < data.length - 1) {
sb.append(", ");
// 每12个元素换行
if ((i + 1) % 12 == 0) {
sb.append("\n ");
}
}
}
sb.append("\n};");
return sb.toString();
}
/**
* 打印十六进制数据
*/
private static void printHexData(byte[] data) {
for (int i = 0; i < data.length; i++) {
int value = data[i] & 0xFF;
System.out.printf("0x%02X", value);
if (i < data.length - 1) {
System.out.print(", ");
if ((i + 1) % 12 == 0) System.out.println();
}
}
System.out.println();
}
/**
* 生成C文件
*/
public static void generateCFile(byte[] data, String filename, String arrayName) throws IOException {
try (FileWriter writer = new FileWriter(filename)) {
writer.write("/**\n");
writer.write(" * 80*12点阵显示数据\n");
writer.write(" * 数据大小: " + data.length + " 字节\n");
writer.write(" * 分辨率: 80*12 像素\n");
writer.write(" */\n\n");
writer.write("#include <stdint.h>\n\n");
writer.write(String.format("// %s: %d 字节, 80*12 像素\n", arrayName, data.length));
writer.write(String.format("const uint8_t %s[] = {\n ", arrayName));
writeByteArray(writer, data);
writer.write("\n};\n");
}
}
private static void writeByteArray(FileWriter writer, byte[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
int value = data[i] & 0xFF;
writer.write(String.format("0x%02X", value));
if (i < data.length - 1) {
writer.write(", ");
if ((i + 1) % 12 == 0) writer.write("\n ");
}
}
}
}

View File

@ -0,0 +1,373 @@
package com.fuyuanshen.common.core.utils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ImageToCArrayConverter {
/* public static void main(String[] args) {
try {
byte[] imageData = convertImageToCArray("E:\\workspace\\6170_强光_160_80_2.jpg", 160, 80,25600);
System.out.println("长度:"+imageData.length);
// int[] ints =convertHexToDecimal(imageData);
// System.out.println("Image data: " + Arrays.toString(ints));
// writeFile("E:\\workspace\\output.c", imageData,160,80);
// System.out.println("转换成功!");
ArrayList<Integer> intData = new ArrayList<>();
intData.add(2);
buildArr(convertHexToDecimal(imageData),intData);
intData.add(0);
intData.add(0);
intData.add(0);
intData.add(0);
Map<String, Object> map = new HashMap<>();
map.put("instruct", intData);
System.out.println(JSON.toJSONString( map));
} catch (IOException e) {
System.err.println("转换失败: " + e.getMessage());
}
}*/
public static void main(String[] args) throws IOException {
byte[] largeData = convertImageToCArray("E:\\workspace\\demo.png", 160, 80,25600);
System.out.println("长度:"+largeData.length);
System.out.println("原始数据大小: " + largeData.length + " 字节");
// 将25600字节的数据分割成512字节的块
// List<byte[]> chunks = splitByteArrayIntoChunks(largeData, 512);
// printChunkInfo(chunks);
//
// // 打印前几块的数据示例
// System.out.println("\n前3块数据示例十进制显示:");
// for (int i = 0; i < Math.min(50, chunks.size()); i++) {
// System.out.println("块 " + i + ":");
// int[] ints = convertHexToDecimal(chunks.get(i));
// System.out.println(Arrays.toString(ints));
// }
// 示例:获取特定块的数据
byte[] specificChunk = getChunk(largeData, 5, 512); // 获取第6块索引5
System.out.println("第6块数据大小: " + specificChunk.length + " 字节");
// 生成预览图片
// BufferedImage image = convertByteArrayToImage(bitmapData, 12, 80);
// ImageIO.write(image, "PNG", new File("D:\\bitmap_preview.png"));
// System.out.println("成功生成预览图片: D:\\bitmap_preview.png");
//
// // 生成C文件
// generateCFile(bitmapData, "bitmap_data.c", "chinese_text");
}
/**
* 获取指定块的数据
*
* @param data 原始字节数组
* @param chunkIndex 块索引从0开始
* @param chunkSize 每块大小
* @return 指定块的字节数组,如果索引无效则返回空数组
*/
public static byte[] getChunk(byte[] data, int chunkIndex, int chunkSize) {
if (data == null || chunkSize <= 0 || chunkIndex < 0) {
return new byte[0];
}
int start = chunkIndex * chunkSize;
if (start >= data.length) {
return new byte[0]; // 索引超出范围
}
int end = Math.min(start + chunkSize, data.length);
int length = end - start;
byte[] chunk = new byte[length];
System.arraycopy(data, start, chunk, 0, length);
return chunk;
}
public static void buildArr(int[] data,List<Integer> intData){
for (int datum : data) {
intData.add(datum);
}
}
/**
* 打印分块信息
*
* @param chunks 分块后的字节数组列表
*/
public static void printChunkInfo(List<byte[]> chunks) {
System.out.println("总共分割成 " + chunks.size() + "");
for (int i = 0; i < chunks.size(); i++) {
System.out.println("" + i + ": " + chunks.get(i).length + " 字节");
}
}
/**
* 将大字节数组分割成固定大小的块
*
* @param data 原始字节数组
* @param chunkSize 每块大小(字节数)
* @return 分割后的字节数组列表
*/
public static List<byte[]> splitByteArrayIntoChunks(byte[] data, int chunkSize) {
if (data == null || data.length == 0 || chunkSize <= 0) {
return new ArrayList<>();
}
List<byte[]> chunks = new ArrayList<>();
int totalChunks = (int) Math.ceil((double) data.length / chunkSize);
for (int i = 0; i < totalChunks; i++) {
int start = i * chunkSize;
int end = Math.min(start + chunkSize, data.length);
int length = end - start;
byte[] chunk = new byte[length];
System.arraycopy(data, start, chunk, 0, length);
chunks.add(chunk);
}
return chunks;
}
public static int[] convertHexToDecimal(byte[] data) {
if (data == null) {
return new int[0];
}
int[] decimalArray = new int[data.length];
for (int i = 0; i < data.length; i++) {
// 将字节转换为无符号整数(十进制)
decimalArray[i] = data[i] & 0xFF;
}
return decimalArray;
}
public static byte[] convertImageToCArray(InputStream inputStream,
int width, int height, int fixedLength) throws IOException {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(inputStream);
// 调整图片尺寸
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
resizedImage.getGraphics().drawImage(
originalImage, 0, 0, width, height, null);
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = resizedImage.getRGB(x, y);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
// 调整到固定长度
byte[] rawData = byteStream.toByteArray();
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
return result;
}
public static byte[] convertImageToCArray(String inputPath,
int width, int height, int fixedLength) throws IOException {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File(inputPath));
// 调整图片尺寸
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
resizedImage.getGraphics().drawImage(
originalImage, 0, 0, width, height, null);
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = resizedImage.getRGB(x, y);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
// 调整到固定长度
byte[] rawData = byteStream.toByteArray();
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
return result;
}
private static void writeFile(String outputPath, byte[] imageData,int width, int height) throws IOException {
// 生成C语言数组文件
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
// 写入注释行(包含尺寸信息)
String header = String.format("/* 0X10,0X10,0X00,0X%02X,0X00,0X%02X,0X01,0X1B, */\n",
width, height);
fos.write(header.getBytes());
// 写入数组声明
fos.write("const unsigned char gImage_data[] = {\n".getBytes());
// 写入数据每行16个字节
for (int i = 0; i < imageData.length; i++) {
// 写入0X前缀
fos.write(("0X" + String.format("%02X", imageData[i] & 0xFF)).getBytes());
// 添加逗号(最后一个除外)
if (i < imageData.length - 1) {
fos.write(',');
}
// 换行和缩进
if ((i + 1) % 16 == 0) {
fos.write('\n');
} else {
fos.write(' ');
}
}
// 写入数组结尾
fos.write("\n};\n".getBytes());
}
}
/**
* 将字节字符串转换为字节数组
*
* @param byteString 字节字符串,格式如 "[12, 45, 67, ...]"
* @return 字节数组
*/
public static byte[] convertStringToByteArray(String byteString) {
if (byteString == null || byteString.isEmpty()) {
return new byte[0];
}
try {
// 移除方括号
String content = byteString.trim();
if (content.startsWith("[")) {
content = content.substring(1);
}
if (content.endsWith("]")) {
content = content.substring(0, content.length() - 1);
}
// 按逗号分割
String[] byteValues = content.split(",");
byte[] result = new byte[byteValues.length];
// 转换每个值
for (int i = 0; i < byteValues.length; i++) {
String value = byteValues[i].trim();
// 处理可能的进制前缀
if (value.startsWith("0x") || value.startsWith("0X")) {
// 十六进制
result[i] = (byte) Integer.parseInt(value.substring(2), 16);
} else {
// 十进制
int intValue = Integer.parseInt(value);
result[i] = (byte) intValue;
}
}
return result;
} catch (NumberFormatException e) {
System.err.println("解析字节字符串时出错: " + e.getMessage());
return new byte[0];
}
}
/**
* 将字节字符串转换为混合类型的Object数组
*
* @param byteString 字节字符串
* @return Object数组包含不同类型的对象
*/
public static Object[] convertByteStringToMixedObjectArray(String byteString) {
if (byteString == null || byteString.isEmpty()) {
return new Object[0];
}
try {
// 移除方括号(如果存在)
String content = byteString.trim();
if (content.startsWith("[")) {
content = content.substring(1);
}
if (content.endsWith("]")) {
content = content.substring(0, content.length() - 1);
}
// 按逗号分割
String[] byteValues = content.split(",");
Object[] result = new Object[byteValues.length];
// 转换每个值为适当类型的对象
for (int i = 0; i < byteValues.length; i++) {
String value = byteValues[i].trim();
// 处理可能的进制前缀
if (value.startsWith("0x") || value.startsWith("0X")) {
// 十六进制
int intValue = Integer.parseInt(value.substring(2), 16);
result[i] = intValue;
} else {
// 尝试解析为整数
try {
int intValue = Integer.parseInt(value);
// 根据值的范围选择合适的类型
if (intValue >= Byte.MIN_VALUE && intValue <= Byte.MAX_VALUE) {
result[i] = (byte) intValue;
} else if (intValue >= Short.MIN_VALUE && intValue <= Short.MAX_VALUE) {
result[i] = (short) intValue;
} else {
result[i] = intValue;
}
} catch (NumberFormatException e) {
// 如果不是数字,保持为字符串
result[i] = value;
}
}
}
return result;
} catch (Exception e) {
System.err.println("解析字节字符串时出错: " + e.getMessage());
return new Object[0];
}
}
}

View File

@ -1,90 +0,0 @@
package com.fuyuanshen.common.core.utils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageToCArrayConverterUtils {
public static void main(String[] args) {
try {
convertImageToCArray("E:\\workspace\\6170_强光_160_80_2.jpg", "E:\\workspace\\output.c", 160, 80);
System.out.println("转换成功!");
} catch (IOException e) {
System.err.println("转换失败: " + e.getMessage());
}
}
public static void convertImageToCArray(String inputPath, String outputPath,
int width, int height) throws IOException {
// 读取原始图片
BufferedImage originalImage = ImageIO.read(new File(inputPath));
// 调整图片尺寸
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
resizedImage.getGraphics().drawImage(
originalImage, 0, 0, width, height, null);
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int rgb = resizedImage.getRGB(x, y);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
byte[] imageData = byteStream.toByteArray();
// 生成C语言数组文件
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
// 写入注释行(包含尺寸信息)
String header = String.format("/* 0X10,0X10,0X00,0X%02X,0X00,0X%02X,0X01,0X1B, */\n",
width, height);
fos.write(header.getBytes());
// 写入数组声明
fos.write("const unsigned char gImage_data[] = {\n".getBytes());
// 写入数据每行16个字节
for (int i = 0; i < imageData.length; i++) {
// 写入0X前缀
fos.write(("0X" + String.format("%02X", imageData[i] & 0xFF)).getBytes());
// 添加逗号(最后一个除外)
if (i < imageData.length - 1) {
fos.write(',');
}
// 换行和缩进
if ((i + 1) % 16 == 0) {
fos.write('\n');
} else {
fos.write(' ');
}
}
// 写入数组结尾
fos.write("\n};\n".getBytes());
}
}
}

View File

@ -0,0 +1,429 @@
package com.fuyuanshen.common.core.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class ImageWithTextGenerate {
/**
* 生成160*80画布嵌入背景图片并居中显示文字支持自动换行输出RGB565格式数据
*
* @param text 要显示的文字
* @param fixedLength 固定输出长度(字节数)
* @return RGB565格式的图像数据
*/
public static byte[] generate160x80ImageWithText2(String text, InputStream backgroundImageInputStream, int fixedLength) throws IOException {
// 创建160*80的图像
BufferedImage image = new BufferedImage(160, 80, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 绘制白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, 160, 80);
// 如果提供了背景图片,则绘制背景
if (backgroundImageInputStream != null ) {
BufferedImage backgroundImage = ImageIO.read(backgroundImageInputStream);
// 缩放并绘制背景图片以适应160*80画布
g.drawImage(backgroundImage, 0, 0, 160, 80, null);
}
// 设置文字属性
Font font = new Font("宋体", Font.PLAIN, 12); // 可根据需要调整字体大小
g.setFont(font);
g.setColor(new Color(255, 255, 255, (int)(0.6 * 255)));
// 关闭抗锯齿以获得清晰的点阵效果
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
// 获取字体度量信息
FontMetrics metrics = g.getFontMetrics();
int lineHeight = metrics.getHeight();
// 文本换行处理
ArrayList<String> lines = wrapText(text, metrics, 120); // 160为画布宽度
// 计算垂直居中起始位置
int totalTextHeight = lines.size() * lineHeight;
int startY = (80 - totalTextHeight) / 2 + metrics.getAscent();
// 绘制每一行文字
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int lineWidth = metrics.stringWidth(line);
int x = (160 - lineWidth) / 2; // 水平居中
int y = startY + i * lineHeight;
g.drawString(line, x, y);
}
g.dispose();
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int yCoord = 0; yCoord < 80; yCoord++) {
for (int xCoord = 0; xCoord < 160; xCoord++) {
int rgb = image.getRGB(xCoord, yCoord);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g1 = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g1 >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
// 调整到固定长度
byte[] rawData = byteStream.toByteArray();
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
return result;
}
/**
* 生成160*80画布嵌入背景图片并居中显示文字支持自动换行输出RGB565格式数据
*
* @param text 要显示的文字
* @param backgroundImagePath 背景图片路径
* @param fixedLength 固定输出长度(字节数)
* @return RGB565格式的图像数据
*/
public static byte[] generate160x80ImageWithText(String text, String backgroundImagePath, int fixedLength) throws IOException {
// 创建160*80的图像
BufferedImage image = new BufferedImage(160, 80, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 绘制白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, 160, 80);
// 如果提供了背景图片,则绘制背景
if (backgroundImagePath != null && !backgroundImagePath.isEmpty()) {
File backgroundFile = new File(backgroundImagePath);
if (backgroundFile.exists()) {
BufferedImage backgroundImage = ImageIO.read(backgroundFile);
// 缩放并绘制背景图片以适应160*80画布
g.drawImage(backgroundImage, 0, 0, 160, 80, null);
}
}
// 设置文字属性
Font font = new Font("宋体", Font.PLAIN, 12); // 可根据需要调整字体大小
g.setFont(font);
g.setColor(new Color(255, 255, 255, (int)(0.6 * 255)));
// 关闭抗锯齿以获得清晰的点阵效果
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
// 获取字体度量信息
FontMetrics metrics = g.getFontMetrics();
int lineHeight = metrics.getHeight();
// 文本换行处理
ArrayList<String> lines = wrapText(text, metrics, 120); // 160为画布宽度
// 计算垂直居中起始位置
int totalTextHeight = lines.size() * lineHeight;
int startY = (80 - totalTextHeight) / 2 + metrics.getAscent();
// 绘制每一行文字
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
int lineWidth = metrics.stringWidth(line);
int x = (160 - lineWidth) / 2; // 水平居中
int y = startY + i * lineHeight;
g.drawString(line, x, y);
}
g.dispose();
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int yCoord = 0; yCoord < 80; yCoord++) {
for (int xCoord = 0; xCoord < 160; xCoord++) {
int rgb = image.getRGB(xCoord, yCoord);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g1 = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g1 >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
// 调整到固定长度
byte[] rawData = byteStream.toByteArray();
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
return result;
}
/**
* 文本换行处理
*
* @param text 原始文本
* @param metrics 字体度量信息
* @param maxWidth 最大宽度
* @return 换行后的文本行列表
*/
private static ArrayList<String> wrapText(String text, FontMetrics metrics, int maxWidth) {
ArrayList<String> lines = new ArrayList<>();
String[] paragraphs = text.split("\n");
for (String paragraph : paragraphs) {
String[] words = paragraph.split("(?<=\\S)(?=\\s)|(?<=\\s)(?=\\S)");
StringBuilder line = new StringBuilder();
for (String word : words) {
String testLine = line.toString() + word;
int lineWidth = metrics.stringWidth(testLine);
if (lineWidth <= maxWidth) {
line.append(word);
} else {
if (line.length() > 0) {
lines.add(line.toString());
line = new StringBuilder(word);
} else {
// 单个词就超过宽度,需要进一步拆分
lines.addAll(wrapWord(word, metrics, maxWidth));
}
}
}
if (line.length() > 0) {
lines.add(line.toString());
}
}
// 限制最大行数以适应80像素高度
if (lines.size() > 6) { // 假设每行最多13像素高80/13约等于6
return (ArrayList<String>) lines.subList(0, 6);
}
return lines;
}
/**
* 对单个超长词进行拆分
*
* @param word 单词
* @param metrics 字体度量信息
* @param maxWidth 最大宽度
* @return 拆分后的词列表
*/
private static ArrayList<String> wrapWord(String word, FontMetrics metrics, int maxWidth) {
ArrayList<String> result = new ArrayList<>();
StringBuilder current = new StringBuilder();
for (char c : word.toCharArray()) {
String testStr = current.toString() + c;
if (metrics.stringWidth(testStr) <= maxWidth) {
current.append(c);
} else {
if (current.length() > 0) {
result.add(current.toString());
}
current = new StringBuilder(String.valueOf(c));
}
}
if (current.length() > 0) {
result.add(current.toString());
}
return result;
}
/**
* 生成160*80画布嵌入背景图片并居中显示文字输出RGB565格式数据支持InputStream
*
* @param text 要显示的文字
* @param backgroundImageInputStream 背景图片输入流
* @param fixedLength 固定输出长度(字节数)
* @return RGB565格式的图像数据
*/
public static byte[] generate160x80ImageWithText(String text, InputStream backgroundImageInputStream, int fixedLength) throws IOException {
// 创建160*80的图像
BufferedImage image = new BufferedImage(160, 80, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 绘制白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, 160, 80);
// 如果提供了背景图片,则绘制背景
if (backgroundImageInputStream != null) {
BufferedImage backgroundImage = ImageIO.read(backgroundImageInputStream);
// 缩放并绘制背景图片以适应160*80画布
g.drawImage(backgroundImage, 0, 0, 160, 80, null);
}
// 设置文字属性
Font font = new Font("宋体", Font.PLAIN, 16); // 可根据需要调整字体大小
g.setFont(font);
g.setColor(Color.BLACK);
// 关闭抗锯齿以获得清晰的点阵效果
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
// 获取字体度量信息
FontMetrics metrics = g.getFontMetrics();
// 计算文字的宽度和高度
int textWidth = metrics.stringWidth(text);
int textHeight = metrics.getHeight();
// 计算居中位置
int x = (160 - textWidth) / 2; // 水平居中
int y = (80 - textHeight) / 2 + metrics.getAscent(); // 垂直居中
// 绘制文字
g.drawString(text, x, y);
g.dispose();
// 转换像素数据为RGB565格式高位在前
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
for (int yCoord = 0; yCoord < 80; yCoord++) {
for (int xCoord = 0; xCoord < 160; xCoord++) {
int rgb = image.getRGB(xCoord, yCoord);
// 提取RGB分量
int r = (rgb >> 16) & 0xFF;
int g1 = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
// 转换为RGB5655位红6位绿5位蓝
int r5 = (r >> 3) & 0x1F;
int g6 = (g1 >> 2) & 0x3F;
int b5 = (b >> 3) & 0x1F;
// 组合为16位值
int rgb565 = (r5 << 11) | (g6 << 5) | b5;
// 高位在前(大端序)写入字节
byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
byteStream.write(rgb565 & 0xFF); // 低字节
}
}
// 调整到固定长度
byte[] rawData = byteStream.toByteArray();
byte[] result = new byte[fixedLength];
int copyLength = Math.min(rawData.length, fixedLength);
System.arraycopy(rawData, 0, result, 0, copyLength);
return result;
}
/**
* 将RGB565格式的字节数组转换为BufferedImage
*
* @param data RGB565格式的数据
* @param height 图像高度
* @param width 图像宽度
* @return 转换后的BufferedImage
*/
public static BufferedImage convertByteArrayToImage(byte[] data, int height, int width) {
if (data == null || data.length == 0) {
return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}
// 创建图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 处理RGB565数据
int dataIndex = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// 每个像素占2个字节
if (dataIndex + 1 >= data.length) {
return image;
}
// 读取两个字节组成RGB565值
int highByte = data[dataIndex++] & 0xFF;
int lowByte = data[dataIndex++] & 0xFF;
int rgb565 = (highByte << 8) | lowByte;
// 将RGB565转换为RGB888
int r = ((rgb565 >> 11) & 0x1F) << 3;
int g = ((rgb565 >> 5) & 0x3F) << 2;
int b = (rgb565 & 0x1F) << 3;
int rgb = (r << 16) | (g << 8) | b;
image.setRGB(x, y, rgb);
}
}
return image;
}
public static void main(String[] args) throws IOException {
// ... 原有代码 ...
// 测试生成160*80画布嵌入背景图片并居中显示文字
// String text = "现在危险,停止救援紧急撤离至安全区域";
String text = "现在危险,停止救援,紧急撤离至安全区域!";
String backgroundImagePath = "D:\\background.png"; // 替换为实际背景图片路径
byte[] imageData = generate160x80ImageWithText(text, backgroundImagePath, 25600);
System.out.println("生成的160*80 RGB565图像数据:");
System.out.println("数据长度: " + imageData.length + " 字节");
// 生成预览图片
// 生成预览图片
BufferedImage image160x80 = convertByteArrayToImage(imageData, 80, 160);
ImageIO.write(image160x80, "PNG", new File("D:\\bitmap_160x80_preview.png"));
// System.out.println("成功生成160*80预览图片: D:\\bitmap_160x80_preview.png");
// 转换为十进制数组
// int[] decimalArray = convertHexToDecimal(imageData);
// System.out.println("生成的十进制数据前50个:");
// System.out.println(Arrays.toString(Arrays.copyOf(decimalArray, Math.min(50, decimalArray.length))));
//
// // 将数据分割成512字节的块
// List<byte[]> chunks = splitByteArrayIntoChunks(imageData, 512);
// printChunkInfo(chunks);
//
// // 示例:获取特定块的数据
// byte[] specificChunk = getChunk(imageData, 0, 512); // 获取第1块索引0
// System.out.println("第1块数据大小: " + specificChunk.length + " 字节");
}
}

View File

@ -24,6 +24,13 @@ public class DecryptRequestBodyWrapper extends HttpServletRequestWrapper {
private final byte[] body;
/**
* @param request
* @param privateKey
* @param headerFlag encrypt-key
* @throws IOException
*/
public DecryptRequestBodyWrapper(HttpServletRequest request, String privateKey, String headerFlag) throws IOException {
super(request);
// 获取 AES 密码 采用 RSA 加密

View File

@ -19,31 +19,36 @@ public class EncryptUtilsTest {
String s = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKNPuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gAkM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWowcSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99EcvDQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthhYhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3UP8iWi1Qw0Y=";
/**
* encrypt-key
*/
String s1 = EncryptUtils.encryptByRsa("MTIzNDU2Nzg5MGFiY2RlZg==", g);
System.out.println(s1);
System.out.println("-------------s1--------------");
String s2 = EncryptUtils.decryptByRsa("jJPaW7hgFXD/gjdkrfBOEUdXpPZnQg/LZUASoOJAOLU/XRVXO/5666CzyALjw7neK1ujvRuys4MdKCvr9cRARw==", s);
System.out.println(s2);
System.out.println("-------------s2--------------");
String s3 = EncryptUtils.decryptByBase64(s2);
System.out.println(s3);
System.out.println("-------------s2--------------");
String s4 = EncryptUtils.encryptByAes("123456", s3);
System.out.println(s4);
System.out.println("-------------s2--------------");
String s5 = EncryptUtils.decryptByAes(s4, s3);
System.out.println(s5);
System.out.println("-------------s2--------------");
// 1. 构造 LoginBody 对象
PasswordLoginBody loginBody = new PasswordLoginBody();
loginBody.setClientId("e5cd7e4891bf95d1d19206ce24a7b32e");
loginBody.setGrantType("password");
loginBody.setTenantId("894078");
loginBody.setCode("0");
loginBody.setUuid("1c285b27f516486f9535face77023aeb");
loginBody.setCode("2");
loginBody.setUuid("d339659cea5245aab7df92642326218e");
// loginBody.setUsername("admin");
// loginBody.setPassword("admin123");
loginBody.setUsername("dyf");
loginBody.setUsername("fel");
loginBody.setPassword("123456");
// 2. 使用更清晰的方式拼接 JSON 字符串
@ -67,9 +72,12 @@ public class EncryptUtilsTest {
);
/**
* body
*/
String S5 = EncryptUtils.encryptByAes(jsonLoginBody, s3);
System.out.println(S5);
System.out.println("-------------s5--------------");
String S6 = EncryptUtils.decryptByAes(S5, s3);
System.out.println(S6);

View File

@ -37,7 +37,7 @@ public enum BusinessType {
EXPORT,
/**
* 导入
*
*/
IMPORT,

View File

@ -0,0 +1,12 @@
package com.fuyuanshen.common.ratelimiter.annotation;// DeviceRedisKeyAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionAccessAnnotation {
String value() default "";
long timeOut() default 30;
}

View File

@ -0,0 +1,13 @@
package com.fuyuanshen.common.ratelimiter.annotation;// DeviceRedisKeyAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionAccessBatcAnnotation {
String value() default "";
long timeOut() default 30;
long batchMaxTimeOut() default 40;
}

View File

@ -0,0 +1,104 @@
package com.fuyuanshen.common.ratelimiter.aspectj;// DeviceRedisKeyAspect.java
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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;
@Slf4j
@Aspect
@Component
public class FunctionAccessAspect {
// 定义切点拦截带有DeviceRedisKeyAnnotation注解的方法
@Around("@annotation(functionAccessAnnotation)")
public Object addDeviceRedisKey(ProceedingJoinPoint joinPoint, FunctionAccessAnnotation functionAccessAnnotation) throws Throwable {
Object result;
String deviceImei = null;
// 获取方法参数查找设备ID
Object[] args = joinPoint.getArgs();
deviceImei = extractDeviceImei(args);
long timeout = functionAccessAnnotation.timeOut();
if (StringUtils.isNotBlank(deviceImei)) {
// 生成全局Redis key
String redisKey = generateDeviceRedisKey(deviceImei);
String cacheKey = RedisUtils.getCacheObject(redisKey);
if(StringUtils.isNotBlank(cacheKey) && "ACTIVE".equals(cacheKey)){
throw new ServiceException("设备已存在访问限制,请稍后再试", 500);
}
//
RedisUtils.setCacheObject(redisKey, "ACTIVE", Duration.ofSeconds(timeout));
}
// 执行原方法
result = joinPoint.proceed();
return result;
}
/**
* 从方法参数中提取设备ID
*/
private String extractDeviceImei(Object[] args) {
if (args == null || args.length == 0) {
return null;
}
for (Object arg : args) {
if (arg == null) continue;
// 如果参数本身就是设备ID (Long类型)
if (arg instanceof Long) {
return arg.toString();
}
// 如果参数是对象尝试获取deviceId字段
try {
// 使用反射获取deviceId字段
java.lang.reflect.Field[] fields = arg.getClass().getDeclaredFields();
for (java.lang.reflect.Field field : fields) {
if ("deviceImei".equalsIgnoreCase(field.getName()) ||
"device_imei".equalsIgnoreCase(field.getName())) {
field.setAccessible(true);
Object value = field.get(arg);
if (value != null) {
return value.toString();
}
}
}
// 尝试获取getId方法
try {
java.lang.reflect.Method getIdMethod = arg.getClass().getMethod("getDeviceImei");
Object value = getIdMethod.invoke(arg);
if (value != null) {
return value.toString();
}
} catch (Exception ignored) {}
} catch (Exception e) {
log.debug("从参数中提取设备ID时出错: {}", e.getMessage());
}
}
return null;
}
/**
* 生成设备的全局Redis key
*/
private String generateDeviceRedisKey(String deviceImei) {
return FUNCTION_ACCESS_KEY + deviceImei;
}
}

View File

@ -0,0 +1,183 @@
package com.fuyuanshen.common.ratelimiter.aspectj;// DeviceRedisKeyAspect.java
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.List;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
@Slf4j
@Aspect
@Component
public class FunctionAccessBatchAspect {
// 定义切点拦截带有DeviceRedisKeyAnnotation注解的方法
@Around("@annotation(functionAccessBatchAspect)")
public Object addDeviceRedisKey(ProceedingJoinPoint joinPoint, FunctionAccessBatcAnnotation functionAccessBatchAspect) throws Throwable {
Object result;
String batchId = null;
List<String> deviceImeiList = null;
// 获取方法参数查找设备ID
Object[] args = joinPoint.getArgs();
batchId = extractDeviceBatchId(args);
deviceImeiList = extractDeviceImeiList(args);
if (StringUtils.isNotBlank(batchId)) {
// 生成全局Redis key
String redisKey = generateDeviceRedisKey(batchId);
String cacheKey = RedisUtils.getCacheObject(redisKey);
if(StringUtils.isNotBlank(cacheKey) && "ACTIVE".equals(cacheKey)){
throw new ServiceException("设备已存在访问限制,请稍后再试", 500);
}
deviceImeiList.forEach(item->{
RedisUtils.setCacheObject(FUNCTION_ACCESS_KEY + item, "ACTIVE", Duration.ofSeconds(functionAccessBatchAspect.timeOut()));
});
String deviceImeiListStr = JSONUtil.toJsonStr(deviceImeiList);
RedisUtils.setCacheObject(redisKey, deviceImeiListStr , Duration.ofSeconds(functionAccessBatchAspect.batchMaxTimeOut()));
}
// 执行原方法
result = joinPoint.proceed();
return result;
}
/**
* 从方法参数中提取设备IMEI列表
*/
private List<String> extractDeviceImeiList(Object[] args) {
if (args == null || args.length == 0) {
return null;
}
for (Object arg : args) {
if (arg == null) continue;
// 如果参数本身就是List<String>类型
if (arg instanceof List) {
List<?> list = (List<?>) arg;
if (!list.isEmpty() && list.get(0) instanceof String) {
// 检查是否为deviceImeiList
return (List<String>) list;
}
}
// 如果参数是对象尝试获取deviceImeiList字段
try {
// 使用反射获取deviceImeiList字段
java.lang.reflect.Field[] fields = arg.getClass().getDeclaredFields();
for (java.lang.reflect.Field field : fields) {
if ("deviceImeiList".equalsIgnoreCase(field.getName()) ||
"device_imei_list".equalsIgnoreCase(field.getName()) ||
"deviceImeis".equalsIgnoreCase(field.getName()) ||
"device_imeis".equalsIgnoreCase(field.getName())) {
field.setAccessible(true);
Object value = field.get(arg);
if (value instanceof List) {
List<?> list = (List<?>) value;
if (!list.isEmpty() && list.get(0) instanceof String) {
return (List<String>) list;
}
}
}
}
// 尝试获取getDeviceImeiList方法
try {
java.lang.reflect.Method getDeviceImeiListMethod = arg.getClass().getMethod("getDeviceImeiList");
Object value = getDeviceImeiListMethod.invoke(arg);
if (value instanceof List) {
List<?> list = (List<?>) value;
if (!list.isEmpty() && list.get(0) instanceof String) {
return (List<String>) list;
}
}
} catch (Exception ignored) {}
// 尝试获取getDeviceImeis方法
try {
java.lang.reflect.Method getDeviceImeisMethod = arg.getClass().getMethod("getDeviceImeis");
Object value = getDeviceImeisMethod.invoke(arg);
if (value instanceof List) {
List<?> list = (List<?>) value;
if (!list.isEmpty() && list.get(0) instanceof String) {
return (List<String>) list;
}
}
} catch (Exception ignored) {}
} catch (Exception e) {
log.debug("从参数中提取设备IMEI列表时出错: {}", e.getMessage());
}
}
return null;
}
/**
* 从方法参数中提取设备ID
*/
private String extractDeviceBatchId(Object[] args) {
if (args == null || args.length == 0) {
return null;
}
for (Object arg : args) {
if (arg == null) continue;
// 如果参数本身就是设备ID (Long类型)
if (arg instanceof Long) {
return arg.toString();
}
// 如果参数是对象尝试获取deviceId字段
try {
// 使用反射获取deviceId字段
java.lang.reflect.Field[] fields = arg.getClass().getDeclaredFields();
for (java.lang.reflect.Field field : fields) {
if ("batchId".equalsIgnoreCase(field.getName()) ||
"batch_id".equalsIgnoreCase(field.getName())) {
field.setAccessible(true);
Object value = field.get(arg);
if (value != null) {
return value.toString();
}
}
}
// 尝试获取getId方法
try {
java.lang.reflect.Method getIdMethod = arg.getClass().getMethod("batchId");
Object value = getIdMethod.invoke(arg);
if (value != null) {
return value.toString();
}
} catch (Exception ignored) {}
} catch (Exception e) {
log.debug("从参数中提取批次号时出错: {}", e.getMessage());
}
}
return null;
}
/**
* 生成设备的全局Redis key
*/
private String generateDeviceRedisKey(String batchId) {
return FUNCTION_ACCESS_KEY + batchId;
}
}

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