0
0

48 Commits

Author SHA1 Message Date
0b5514d814 Merge branch 'main' into fys-main 2025-08-04 09:37:07 +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
a4d2f548d3 Merge branch 'main' into fys-main 2025-08-04 09:11:07 +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
fc3626e1a1 Merge branch 'main' into fys-main 2025-07-31 09:25:09 +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
3450b025b4 设备报警记录 2025-07-29 15:21:27 +08:00
984081ac98 设备日志 2025-07-29 11:10:03 +08:00
5b3ea9faf5 设备报警记录 2025-07-29 11:02:09 +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
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
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
8750bc8e10 Merge remote-tracking branch 'upstream/main' 2025-07-21 08:43:34 +08:00
879e485056 Merge branch 'dyf-device' 2025-07-21 08:39:55 +08:00
69c4cc2004 APP设备分享功能开发2 2025-07-19 14:28:07 +08:00
a7340c744e APP客户设备绑定-绑定时间 2025-07-19 14:22:36 +08:00
94 changed files with 5438 additions and 278 deletions

View File

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

View File

@ -92,7 +92,14 @@ public class AppAuthController {
}
/**
* 用户注销
*/
@DeleteMapping("/cancelAccount")
public R<Void> cancelAccount() {
loginService.cancelAccount();
return R.ok("用户注销成功");
}
/**
* 退出登录

View File

@ -1,7 +1,11 @@
package com.fuyuanshen.app.controller;
import cn.hutool.json.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.app.service.AppDeviceBizService;
@ -11,14 +15,17 @@ 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.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* APP设备信息管理
@ -37,7 +44,6 @@ public class AppDeviceController extends BaseController {
*/
@GetMapping("/list")
public TableDataInfo<AppDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return appDeviceService.queryAppDeviceList(bo,pageQuery);
}
@ -101,7 +107,63 @@ public class AppDeviceController extends BaseController {
* 发送信息
*/
@PostMapping(value = "/sendMessage")
public R<Void> sendMessage(@RequestBody AppDeviceBo bo) {
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
return toAjax(appDeviceService.sendMessage(bo));
}
/**
* 上传设备logo图片
*/
@PostMapping("/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泛光模式
*/
@PostMapping("/lightModeSettings")
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.lightModeSettings(params);
return R.ok();
}
/**
* 灯光亮度设置
*
*/
@PostMapping("/lightBrightnessSettings")
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.lightBrightnessSettings(params);
return R.ok();
}
/**
* 激光模式设置
*
*/
@PostMapping("/laserModeSettings")
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
appDeviceService.laserModeSettings(params);
return R.ok();
}
/**
* 地图逆解析
*
*/
@PostMapping("/mapReverseGeocoding")
public R<Void> mapReverseGeocoding(@RequestBody DeviceInstructDto params) {
String mapJson = appDeviceService.mapReverseGeocoding(params);
return R.ok(mapJson);
}
}

View File

@ -55,6 +55,14 @@ public class AppDeviceShareController extends BaseController {
return deviceShareService.queryPageList(bo, pageQuery);
}
/**
* 他人分享管理列表
*/
@GetMapping("/otherDeviceShareList")
public TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery) {
return deviceShareService.otherDeviceShareList(bo, pageQuery);
}
/**
* 获取设备分享详细信息
*

View File

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

@ -1,35 +1,54 @@
package com.fuyuanshen.app.service;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.app.mapper.equipment.APPDeviceMapper;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.MapstructUtils;
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.DeviceType;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.utils.c.ReliableTextToBitmap;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.List;
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.ImageToCArrayConverter.convertHexToDecimal;
@Slf4j
@ -41,7 +60,8 @@ public class AppDeviceBizService {
private final DeviceMapper deviceMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final MqttGateway mqttGateway;
private final AppDeviceBindRecordMapper appDeviceBindRecordMapper;
public List<APPDeviceTypeVo> getTypeList() {
Long userId = AppLoginHelper.getUserId();
@ -57,12 +77,31 @@ public class AppDeviceBizService {
}
public int sendMessage(AppDeviceBo bo) {
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", bo.getDeviceId())
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("send_msg", bo.getSendMsg());
return deviceMapper.update(updateWrapper);
public int sendMessage(AppDeviceSendMsgBo bo) {
List<Long> deviceIds = bo.getDeviceIds();
if(deviceIds == null || deviceIds.isEmpty()){
throw new ServiceException("请选择设备");
}
for (Long deviceId : deviceIds){
Device deviceObj = deviceMapper.selectById(deviceId);
if(deviceObj==null) {
throw new ServiceException("设备不存在"+deviceId);
}
byte[] msg = ReliableTextToBitmap.textToBitmapBytes(bo.getSendMsg());
Map<String,Object> linkHashMap = new HashMap<>();
linkHashMap.put("message",msg);
String sendMsg = JSON.toJSONString(linkHashMap);
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY+deviceObj.getDeviceImei(), 1 ,sendMsg);
log.info("发送设备消息:{}", bo.getSendMsg());
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", deviceId)
.eq("binding_user_id", AppLoginHelper.getUserId())
.set("send_msg", bo.getSendMsg());
deviceMapper.update(updateWrapper);
}
return 1;
}
@ -96,8 +135,6 @@ public class AppDeviceBizService {
.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();
@ -108,9 +145,27 @@ public class AppDeviceBizService {
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());
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())
@ -123,7 +178,12 @@ public class AppDeviceBizService {
}
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("请先将设备入库!!!");
@ -133,11 +193,38 @@ public class AppDeviceBizService {
.set("binding_status", BindingStatusEnum.UNBOUND.getCode())
.set("binding_user_id", null)
.set("binding_time", null);
return deviceMapper.update(null, deviceUpdateWrapper);
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()));
}
return 1;
}
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());
@ -146,14 +233,18 @@ public class AppDeviceBizService {
vo.setDeviceMac(device.getDeviceMac());
vo.setDeviceStatus(device.getDeviceStatus());
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
if(deviceType!=null){
if (deviceType != null) {
vo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
vo.setTypeName(deviceType.getTypeName());
}
vo.setBluetoothName(device.getBluetoothName());
AppPersonnelInfo appPersonnelInfo = appPersonnelInfoMapper.selectById(device.getId());
if(appPersonnelInfo != null){
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);
}
@ -161,7 +252,177 @@ public class AppDeviceBizService {
}
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
return appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
Long deviceId = bo.getDeviceId();
Device deviceObj = deviceMapper.selectById(deviceId);
if(deviceObj == null){
throw new RuntimeException("请先将设备入库!!!");
}
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
.eq("device_id", deviceId);
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
// unitName,position,name,id
byte[] unitName = ReliableTextToBitmap.textToBitmapBytes(bo.getUnitName());
byte[] position = ReliableTextToBitmap.textToBitmapBytes(bo.getPosition());
byte[] name = ReliableTextToBitmap.textToBitmapBytes(bo.getName());
byte[] id = ReliableTextToBitmap.textToBitmapBytes(bo.getCode());
Map<String,Object> linkHashMap = new HashMap<>();
linkHashMap.put("unitName",unitName);
linkHashMap.put("position",position);
linkHashMap.put("name",name);
linkHashMap.put("id",id);
String personnelInfo = JSON.toJSONString(linkHashMap);
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY+deviceObj.getDeviceImei(), 1 ,personnelInfo);
log.info("发送点阵数据到设备消息:{}", bo);
if (ObjectUtils.length(appPersonnelInfoVos) == 0) {
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
return appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
} else {
UpdateWrapper<AppPersonnelInfo> uw = new UpdateWrapper<>();
uw.eq("device_id", deviceId)
.set("name", bo.getName())
.set("position", bo.getPosition())
.set("unit_name", bo.getUnitName())
.set("code", bo.getCode());
return appPersonnelInfoMapper.update(null, uw) > 0;
}
}
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
try {
Device device = deviceMapper.selectById(bo.getDeviceId());
if (device == null) {
throw new ServiceException("设备不存在");
}
MultipartFile file = bo.getFile();
byte[] largeData = ImageToCArrayConverter.convertImageToCArray(file.getInputStream(), 160, 80, 25600);
System.out.println("长度:" + largeData.length);
System.out.println("原始数据大小: " + largeData.length + " 字节");
int[] ints = convertHexToDecimal(largeData);
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY+"app_logo_data:" + device.getDeviceImei(), Arrays.toString(ints), Duration.ofSeconds(30 * 60L));
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+"app_logo_data:" + device.getDeviceImei());
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
System.out.println("第0块数据大小: " + specificChunk.length + " 字节");
System.out.println("第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));
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 灯光模式
* 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("设备不存在");
}
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));
} catch (Exception e){
e.printStackTrace();
}
}
//灯光亮度设置
public void lightBrightnessSettings(DeviceInstructDto params) {
try {
Long deviceId = params.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if(device == null){
throw new ServiceException("设备不存在");
}
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();
}
}
//激光模式设置
public void laserModeSettings(DeviceInstructDto params) {
try {
Long deviceId = params.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if(device == null){
throw new ServiceException("设备不存在");
}
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));
} catch (Exception e){
e.printStackTrace();
}
}
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());
}
}

View File

@ -95,7 +95,10 @@ public class AppDeviceShareService {
return code.equals(smsCode);
}
public int deviceShare(AppDeviceShareBo bo) {
validateSmsCode(AppLoginHelper.getTenantId(), bo.getPhonenumber(), bo.getSmsCode());
boolean flag = validateSmsCode(AppLoginHelper.getTenantId(), bo.getPhonenumber(), bo.getSmsCode());
if(!flag){
throw new ServiceException("验证码错误");
}
Device device = deviceMapper.selectById(bo.getDeviceId());
if(device==null){

View File

@ -28,10 +28,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.*;
import java.util.function.Supplier;
/**
@ -51,7 +48,7 @@ public class AppLoginService {
private Integer lockTime;
private final ISysTenantService tenantService;
private final IAppRoleService roleService;
private final IAppUserService appUserService;
/**
@ -184,5 +181,24 @@ public class AppLoginService {
throw new TenantException("tenant.expired");
}
}
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,39 @@
package com.fuyuanshen.global.mqtt.base;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
/**
* MQTT消息引擎
*/
@Component
public class MqttRuleEngine {
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) {
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,4 +1,4 @@
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;

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,76 @@
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";
/**
* 定位数据 (Location Data)
*/
public static final String LOCATION_DATA = "Light_11";
/**
* 主动上报设备数据 (Active Reporting Device Data)
*/
public static final String ACTIVE_REPORTING_DEVICE_DATA = "Light_12";
/**
* 获取命令类型描述
*
* @param commandType 命令类型
* @return 命令类型描述
*/
public static String getCommandTypeDescription(String commandType) {
return switch (commandType) {
case LIGHT_MODE -> "灯光模式 (Light Mode)";
case PERSONNEL_INFO -> "人员信息 (Personnel Information)";
case BOOT_LOGO -> "开机LOGO (Boot Logo)";
case LASER_LIGHT -> "激光灯 (Laser Light)";
case MAIN_LIGHT_BRIGHTNESS -> "主灯亮度 (Main Light Brightness)";
case LOCATION_DATA -> "定位数据 (Location Data)";
default -> "未知命令类型 (Unknown Command Type)";
};
}
/**
* 检查是否为有效命令类型
*
* @param commandType 命令类型
* @return 是否有效
*/
public static boolean isValidCommandType(String commandType) {
return commandType.equals(LIGHT_MODE) ||
commandType.equals(PERSONNEL_INFO) ||
commandType.equals(BOOT_LOGO) ||
commandType.equals(LASER_LIGHT) ||
commandType.equals(MAIN_LIGHT_BRIGHTNESS) ||
commandType.equals(LOCATION_DATA);
}
}

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

@ -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,6 +1,6 @@
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;

View File

@ -0,0 +1,63 @@
package com.fuyuanshen.global.mqtt.receiver;
import cn.hutool.core.lang.Dict;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.base.MqttRuleEngine;
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.util.Objects;
@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 state = payloadDict.getStr("state");
Object[] convertArr = ImageToCArrayConverter.convertByteStringToMixedObjectArray(state);
if (convertArr.length > 0) {
Byte val1 = (Byte) convertArr[0];
String[] subStr = receivedTopic.split("/");
System.out.println("收到设备id: " + subStr[1]);
String deviceImei = subStr[1];
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,95 @@
package com.fuyuanshen.global.mqtt.rule;
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 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;
/**
* 主动上报设备数据命令处理
* "第1位为12表示设备主动上报设备硬件状态第2为表示当时设备主灯档位第3位表示当时激光灯档位第4位电量百分比第5位为充电状态0没有充电1正在充电2为已充满
* 第6位200代表电池剩余续航时间200分钟"
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class ActiveReportingDeviceDataRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@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使用CompletableFuture
*
* @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 = "device:status:" + deviceImei;
String deviceInfoJson = JsonUtils.toJsonString(deviceInfo);
// 存储到Redis设置过期时间例如24小时
RedisUtils.setCacheObject(deviceRedisKey, deviceInfoJson, Duration.ofSeconds(24 * 60 * 60));
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,149 @@
package com.fuyuanshen.global.mqtt.rule;
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.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
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;
/**
* 定位数据命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class LocationDataRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.LOCATION_DATA;
}
@Override
public void execute(MqttRuleContext context) {
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));
} catch (Exception e) {
log.error("处理定位数据命令时出错", e);
}
}
/**
* 异步发送位置信息到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.isNotBlank(latitude) || StringUtils.isNotBlank(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]);
String address = GetAddressFromLatUtil.getAdd(String.valueOf(doubles[1]), String.valueOf(doubles[0]));
locationInfo.put("address", address);
locationInfo.put("timestamp", System.currentTimeMillis());
// 将位置信息存储到Redis中
String redisKey = "device:location:" + deviceImei;
String locationJson = JsonUtils.toJsonString(locationInfo);
// 存储到Redis
RedisUtils.setCacheObject(redisKey, locationJson, Duration.ofSeconds(24 * 60 * 60));
log.info("位置信息已异步发送到Redis: device={}, lat={}, lon={}", deviceImei, latitude, longitude);
} catch (Exception e) {
log.error("异步发送位置信息到Redis时出错: 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]));
intData.add(Integer.parseInt(latArr[1]));
intData.add(Integer.parseInt(lonArr[0]));
intData.add(Integer.parseInt(lonArr[1]));
Map<String, Object> map = new HashMap<>();
map.put("instruct", intData);
return map;
}
}

View File

@ -0,0 +1,76 @@
package com.fuyuanshen.global.mqtt.rule;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
/**
* 人员信息命令处理
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class PersonnelInfoRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
@Override
public String getCommandType() {
return LightingCommandTypeConstants.PERSONNEL_INFO;
}
@Override
public void execute(MqttRuleContext context) {
try {
Byte val2 = (Byte) context.getConvertArr()[1];
if (val2 == 100) {
return;
}
String data = RedisUtils.getCacheObject("894078:app_logo_data:" + context.getDeviceImei());
if (StringUtils.isEmpty(data)) {
return;
}
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, (val2 - 1), 512);
System.out.println("" + val2 + "块数据大小: " + specificChunk.length + " 字节");
System.out.println("" + val2 + "块数据: " + Arrays.toString(specificChunk));
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("发送人员信息点阵数据到设备消息=>topic:{},payload:{}",
MqttConstants.GLOBAL_PUB_KEY + context.getDeviceImei(),
JsonUtils.toJsonString(map));
} catch (Exception e) {
log.error("处理人员信息命令时出错", e);
}
}
}

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

@ -0,0 +1,46 @@
package com.fuyuanshen.web.controller.device;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.web.service.WEBDeviceService;
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.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @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;
/**
* @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));
}
}

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,264 @@
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.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.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 payload = message.getPayload().toString();
if (receivedTopicName != null) {
// 1. 提取设备ID (从主题中获取)
String deviceImei = extractDeviceId(receivedTopicName);
Device device = deviceMapper.selectOne(new QueryWrapper<Device>().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("客户端操作");
}
}
deviceLogMapper.insert(record);
}
if (root.has("imei")) {
// 设备行为
record.setDeviceAction(InstructType6170.fromCode(0).getDescription());
record.setDataSource("设备上报");
record.setContent("设备启动");
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 StateRecord parseState(Device device, JsonNode array) {
// StateRecord record = new StateRecord();
// record.setDevice(device);
// record.setStateType(array.get(0).asInt());
//
// switch (record.getStateType()) {
// case 1: // 灯光状态
// record.setLightMode(array.get(1).asInt());
// record.setBrightness(array.get(2).asInt());
// break;
//
// case 2: // 设置结果
// record.setSetResult(array.get(1).asInt() == 1);
// break;
//
// case 3: // 图片更新状态
// record.setImagePage(array.get(1).asInt());
// break;
//
// case 4: // 激光灯状态
// record.setLaserStatus(array.get(1).asInt() == 1);
// break;
//
// case 5: // 亮度状态
// record.setBrightness(array.get(1).asInt());
// break;
//
// case 11: // 定位上报
// record.setLatitude(array.get(1).asDouble());
// record.setLongitude(array.get(2).asDouble());
// break;
//
// case 12: // 设备状态
// record.setMainLightGear(array.get(1).asInt());
// record.setLaserLightGear(array.get(2).asInt());
// record.setBattery(array.get(3).asInt());
// record.setChargeStatus(array.get(4).asInt());
// record.setDuration(array.get(5).asInt());
// break;
// }
// return record;
// }
}

View File

@ -7,6 +7,7 @@ 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;
@ -47,6 +48,7 @@ public class AppRegisterService {
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("该手机号已被注册");
@ -67,7 +69,7 @@ public class AppRegisterService {
appUser.setNickName(username);
appUser.setPhonenumber(phoneNumber);
appUser.setPassword(password);
appUser.setUserType("app_user");
appUser.setUserType(UserType.APP_USER.getUserType());
appUser.setTenantId(tenantId);
appUser.setLoginIp(ServletUtils.getClientIP());
appUser.setStatus("0");

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

@ -14,6 +14,7 @@ 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;
@ -108,7 +109,9 @@ public class AppPasswordAuthStrategy implements IAuthStrategy {
}
private AppUserVo loadUserByUsername(String username) {
AppUserVo user = appUserMapper.selectVoOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUserName, 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);

View File

@ -59,6 +59,7 @@ public class AppSmsAuthStrategy implements IAuthStrategy {
if (ObjectUtil.isNull(user)) {
//新增Appuser
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));
@ -70,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 配置

View File

@ -0,0 +1,51 @@
package com.fuyuanshen.web.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.app.service.AppDeviceBizService;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.web.service.WEBDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* @Description:
* @Author: WY
* @Date: 2025/5/16
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class WEBDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements WEBDeviceService {
private final AppDeviceBizService appDeviceService;
private final DeviceAssignmentsMapper deviceAssignmentsMapper;
/**
* WEB端解绑设备
*
* @param id
* @return
*/
@Override
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;
}
return appDeviceService.unBindDevice(id, userId, type);
}
}

View File

@ -303,6 +303,6 @@ mqtt:
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

View File

@ -177,11 +177,14 @@ sms:
# 框架定义的厂商名称标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
supplier: alibaba
# 有些称为accessKey有些称之为apiKey也有称为sdkKey或者appId。
access-key-id: 您的accessKey
access-key-id: LTAI5tJdDNpZootsPQ5hdELx
# 称为accessSecret有些称之为apiSecret
access-key-secret: 您的accessKeySecret
signature: 您的短信签名
sdk-app-id: 您的sdkAppId
access-key-secret: mU4WtffcCXpHPz5tLwQpaGtLsJXONt
#模板ID 非必须配置如果使用sendMessage的快速发送需此配置
template-id: SMS_322180518
#模板变量 上述模板的变量
templateName: code
signature: 湖北星汉研创科技
config2:
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
supplier: tencent
@ -277,11 +280,11 @@ 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

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);
}
private 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\\6170_强光_160_80_2.jpg", 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,105 @@
package com.fuyuanshen.app.controller;
import java.util.List;
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.mybatis.core.page.PageQuery;
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.app.domain.vo.AppDeviceBindRecordVo;
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
import com.fuyuanshen.app.service.IAppDeviceBindRecordService;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
/**
* 设备绑定关系
*
* @author Lion Li
* @date 2025-07-28
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/deviceBindRecord")
public class AppDeviceBindRecordController extends BaseController {
private final IAppDeviceBindRecordService appDeviceBindRecordService;
/**
* 查询设备绑定关系列表
*/
@SaCheckPermission("app:deviceBindRecord:list")
@GetMapping("/list")
public TableDataInfo<AppDeviceBindRecordVo> list(AppDeviceBindRecordBo bo, PageQuery pageQuery) {
return appDeviceBindRecordService.queryPageList(bo, pageQuery);
}
/**
* 导出设备绑定关系列表
*/
@SaCheckPermission("app:deviceBindRecord:export")
@Log(title = "设备绑定关系", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(AppDeviceBindRecordBo bo, HttpServletResponse response) {
List<AppDeviceBindRecordVo> list = appDeviceBindRecordService.queryList(bo);
ExcelUtil.exportExcel(list, "设备绑定关系", AppDeviceBindRecordVo.class, response);
}
/**
* 获取设备绑定关系详细信息
*
* @param id 主键
*/
@SaCheckPermission("app:deviceBindRecord:query")
@GetMapping("/{id}")
public R<AppDeviceBindRecordVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(appDeviceBindRecordService.queryById(id));
}
/**
* 新增设备绑定关系
*/
@SaCheckPermission("app:deviceBindRecord:add")
@Log(title = "设备绑定关系", businessType = BusinessType.INSERT)
@RepeatSubmit()
@PostMapping()
public R<Void> add(@Validated(AddGroup.class) @RequestBody AppDeviceBindRecordBo bo) {
return toAjax(appDeviceBindRecordService.insertByBo(bo));
}
/**
* 修改设备绑定关系
*/
@SaCheckPermission("app:deviceBindRecord:edit")
@Log(title = "设备绑定关系", businessType = BusinessType.UPDATE)
@RepeatSubmit()
@PutMapping()
public R<Void> edit(@Validated(EditGroup.class) @RequestBody AppDeviceBindRecordBo bo) {
return toAjax(appDeviceBindRecordService.updateByBo(bo));
}
/**
* 删除设备绑定关系
*
* @param ids 主键串
*/
@SaCheckPermission("app:deviceBindRecord:remove")
@Log(title = "设备绑定关系", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(appDeviceBindRecordService.deleteWithValidByIds(List.of(ids), true));
}
}

View File

@ -0,0 +1,53 @@
package com.fuyuanshen.app.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fuyuanshen.common.tenant.core.TenantEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serial;
import java.util.Date;
/**
* 设备绑定关系对象 app_device_bind_record
*
* @author Lion Li
* @date 2025-07-28
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("app_device_bind_record")
public class AppDeviceBindRecord extends TenantEntity {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId(value = "id")
private Long id;
/**
* 设备id
*/
private Long deviceId;
/**
* 绑定用户id
*/
private Long bindingUserId;
/**
* 备注
*/
private String remark;
/**
* 绑定时间
*/
private Date bindingTime;
}

View File

@ -36,6 +36,11 @@ public class AppPersonnelInfo extends TenantEntity {
*/
private String name;
/**
* 职位
*/
private String position;
/**
* 单位名称
*/
@ -46,5 +51,6 @@ public class AppPersonnelInfo extends TenantEntity {
*/
private String sendMsg;
private String code;
}

View File

@ -0,0 +1,51 @@
package com.fuyuanshen.app.domain.bo;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.common.core.validate.EditGroup;
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import jakarta.validation.constraints.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 设备绑定关系业务对象 app_device_bind_record
*
* @author Lion Li
* @date 2025-07-28
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AutoMapper(target = AppDeviceBindRecord.class, reverseConvertGenerate = false)
public class AppDeviceBindRecordBo extends BaseEntity {
/**
* 主键ID
*/
@NotNull(message = "主键ID不能为空", groups = { EditGroup.class })
private Long id;
/**
* 设备id
*/
private Long deviceId;
/**
* 绑定用户id
*/
private Long bindingUserId;
/**
* 备注
*/
private String remark;
/**
* 绑定时间
*/
private Date bindingTime;
}

View File

@ -23,13 +23,11 @@ public class AppPersonnelInfoBo extends BaseEntity {
/**
* 主键
*/
@NotNull(message = "主键不能为空", groups = { AddGroup.class, EditGroup.class })
private Long id;
/**
* 设备id
*/
@NotNull(message = "设备id不能为空", groups = { AddGroup.class, EditGroup.class })
private Long deviceId;
/**
@ -37,6 +35,11 @@ public class AppPersonnelInfoBo extends BaseEntity {
*/
private String name;
/**
* 职位
*/
private String position;
/**
* 部门名称
*/
@ -52,5 +55,8 @@ public class AppPersonnelInfoBo extends BaseEntity {
*/
private String sendMsg;
/**
* ID号
*/
private String code;
}

View File

@ -0,0 +1,64 @@
package com.fuyuanshen.app.domain.vo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
import cn.idev.excel.annotation.ExcelProperty;
import com.fuyuanshen.common.excel.annotation.ExcelDictFormat;
import com.fuyuanshen.common.excel.convert.ExcelDictConvert;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* 设备绑定关系视图对象 app_device_bind_record
*
* @author Lion Li
* @date 2025-07-28
*/
@Data
@ExcelIgnoreUnannotated
@AutoMapper(target = AppDeviceBindRecord.class)
public class AppDeviceBindRecordVo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@ExcelProperty(value = "主键ID")
private Long id;
/**
* 设备id
*/
@ExcelProperty(value = "设备id")
private Long deviceId;
/**
* 绑定用户id
*/
@ExcelProperty(value = "绑定用户id")
private Long bindingUserId;
/**
* 备注
*/
@ExcelProperty(value = "备注")
private String remark;
/**
* 绑定时间
*/
@ExcelProperty(value = "绑定时间")
private Date bindingTime;
}

View File

@ -69,4 +69,9 @@ public class AppDeviceDetailVo {
* 人员信息
*/
private AppPersonnelInfoVo personnelInfo;
/**
* 发送信息
*/
private String sendMsg;
}

View File

@ -41,6 +41,10 @@ public class AppDeviceShareVo implements Serializable {
@ExcelProperty(value = "设备ID")
private Long deviceId;
/**
* 设备IMEI
*/
private String deviceImei;
/**
* 设备名称
*/

View File

@ -47,10 +47,10 @@ public class AppPersonnelInfoVo implements Serializable {
private String name;
/**
* 部门名称
* 岗位
*/
@ExcelProperty(value = "部门名称")
private String deptName;
@ExcelProperty(value = "岗位")
private String position;
/**
* 单位名称
@ -59,10 +59,10 @@ public class AppPersonnelInfoVo implements Serializable {
private String unitName;
/**
* 发送信息
* ID号
*/
@ExcelProperty(value = "发送信息")
private String sendMsg;
@ExcelProperty(value = "ID号")
private String code;
}

View File

@ -0,0 +1,15 @@
package com.fuyuanshen.app.mapper;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
/**
* 设备绑定关系Mapper接口
*
* @author Lion Li
* @date 2025-07-28
*/
public interface AppDeviceBindRecordMapper extends BaseMapperPlus<AppDeviceBindRecord, AppDeviceBindRecordVo> {
}

View File

@ -1,8 +1,12 @@
package com.fuyuanshen.app.mapper;
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.bo.AppDeviceShareBo;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
import org.apache.ibatis.annotations.Param;
/**
* 设备分享Mapper接口
@ -11,5 +15,5 @@ import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
* @date 2025-07-16
*/
public interface AppDeviceShareMapper extends BaseMapperPlus<AppDeviceShare, AppDeviceShareVo> {
IPage<AppDeviceShareVo> otherDeviceShareList(@Param("bo") AppDeviceShareBo bo, Page<AppDeviceShareVo> page);
}

View File

@ -0,0 +1,68 @@
package com.fuyuanshen.app.service;
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import java.util.Collection;
import java.util.List;
/**
* 设备绑定关系Service接口
*
* @author Lion Li
* @date 2025-07-28
*/
public interface IAppDeviceBindRecordService {
/**
* 查询设备绑定关系
*
* @param id 主键
* @return 设备绑定关系
*/
AppDeviceBindRecordVo queryById(Long id);
/**
* 分页查询设备绑定关系列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备绑定关系分页列表
*/
TableDataInfo<AppDeviceBindRecordVo> queryPageList(AppDeviceBindRecordBo bo, PageQuery pageQuery);
/**
* 查询符合条件的设备绑定关系列表
*
* @param bo 查询条件
* @return 设备绑定关系列表
*/
List<AppDeviceBindRecordVo> queryList(AppDeviceBindRecordBo bo);
/**
* 新增设备绑定关系
*
* @param bo 设备绑定关系
* @return 是否新增成功
*/
Boolean insertByBo(AppDeviceBindRecordBo bo);
/**
* 修改设备绑定关系
*
* @param bo 设备绑定关系
* @return 是否修改成功
*/
Boolean updateByBo(AppDeviceBindRecordBo bo);
/**
* 校验并批量删除设备绑定关系信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}

View File

@ -65,4 +65,6 @@ public interface IAppDeviceShareService {
* @return 是否删除成功
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery);
}

View File

@ -0,0 +1,133 @@
package com.fuyuanshen.app.service.impl;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.app.service.IAppDeviceBindRecordService;
import java.util.List;
import java.util.Map;
import java.util.Collection;
/**
* 设备绑定关系Service业务层处理
*
* @author Lion Li
* @date 2025-07-28
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class AppDeviceBindRecordServiceImpl implements IAppDeviceBindRecordService {
private final AppDeviceBindRecordMapper baseMapper;
/**
* 查询设备绑定关系
*
* @param id 主键
* @return 设备绑定关系
*/
@Override
public AppDeviceBindRecordVo queryById(Long id){
return baseMapper.selectVoById(id);
}
/**
* 分页查询设备绑定关系列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备绑定关系分页列表
*/
@Override
public TableDataInfo<AppDeviceBindRecordVo> queryPageList(AppDeviceBindRecordBo bo, PageQuery pageQuery) {
LambdaQueryWrapper<AppDeviceBindRecord> lqw = buildQueryWrapper(bo);
Page<AppDeviceBindRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
/**
* 查询符合条件的设备绑定关系列表
*
* @param bo 查询条件
* @return 设备绑定关系列表
*/
@Override
public List<AppDeviceBindRecordVo> queryList(AppDeviceBindRecordBo bo) {
LambdaQueryWrapper<AppDeviceBindRecord> lqw = buildQueryWrapper(bo);
return baseMapper.selectVoList(lqw);
}
private LambdaQueryWrapper<AppDeviceBindRecord> buildQueryWrapper(AppDeviceBindRecordBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<AppDeviceBindRecord> lqw = Wrappers.lambdaQuery();
lqw.orderByAsc(AppDeviceBindRecord::getId);
lqw.eq(bo.getDeviceId() != null, AppDeviceBindRecord::getDeviceId, bo.getDeviceId());
lqw.eq(bo.getBindingUserId() != null, AppDeviceBindRecord::getBindingUserId, bo.getBindingUserId());
lqw.eq(bo.getBindingTime() != null, AppDeviceBindRecord::getBindingTime, bo.getBindingTime());
return lqw;
}
/**
* 新增设备绑定关系
*
* @param bo 设备绑定关系
* @return 是否新增成功
*/
@Override
public Boolean insertByBo(AppDeviceBindRecordBo bo) {
AppDeviceBindRecord add = MapstructUtils.convert(bo, AppDeviceBindRecord.class);
validEntityBeforeSave(add);
boolean flag = baseMapper.insert(add) > 0;
if (flag) {
bo.setId(add.getId());
}
return flag;
}
/**
* 修改设备绑定关系
*
* @param bo 设备绑定关系
* @return 是否修改成功
*/
@Override
public Boolean updateByBo(AppDeviceBindRecordBo bo) {
AppDeviceBindRecord update = MapstructUtils.convert(bo, AppDeviceBindRecord.class);
validEntityBeforeSave(update);
return baseMapper.updateById(update) > 0;
}
/**
* 保存前的数据校验
*/
private void validEntityBeforeSave(AppDeviceBindRecord entity){
//TODO 做一些数据校验,如唯一约束
}
/**
* 校验并批量删除设备绑定关系信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if(isValid){
//TODO 做一些业务上的校验,判断是否需要校验
}
return baseMapper.deleteByIds(ids) > 0;
}
}

View File

@ -1,5 +1,6 @@
package com.fuyuanshen.app.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
@ -68,6 +69,7 @@ public class AppDeviceShareServiceImpl implements IAppDeviceShareService {
if(device != null){
r.setDevicePic(device.getDevicePic());
r.setDeviceName(device.getDeviceName());
r.setDeviceImei(device.getDeviceImei());
}
});
return TableDataInfo.build(result);
@ -146,4 +148,22 @@ public class AppDeviceShareServiceImpl implements IAppDeviceShareService {
}
return baseMapper.deleteByIds(ids) > 0;
}
@Override
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 = baseMapper.otherDeviceShareList(bo, page);
List<AppDeviceShareVo> records = result.getRecords();
records.forEach(r -> {
Device device = deviceMapper.selectById(r.getDeviceId());
if(device != null){
r.setDevicePic(device.getDevicePic());
r.setDeviceName(device.getDeviceName());
r.setDeviceImei(device.getDeviceImei());
}
});
return TableDataInfo.build(result);
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper">
</mapper>

View File

@ -4,4 +4,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fuyuanshen.app.mapper.AppDeviceShareMapper">
<select id="otherDeviceShareList" resultType="com.fuyuanshen.app.domain.vo.AppDeviceShareVo">
SELECT * FROM app_device_share a where a.phonenumber = #{bo.phonenumber}
</select>
</mapper>

View File

@ -92,7 +92,7 @@ public class Customer extends TenantEntity {
/**
* 帐号状态0正常 1停用
*/
private String status;
private String status = "0";
/**
* 删除标志0代表存在 1代表删除

View File

@ -1,9 +1,11 @@
package com.fuyuanshen.customer.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.customer.constant.ArrayConstants;
@ -92,6 +94,7 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
}
customer.setUserLevel((byte) (loginUser.getUserLevel() + 1));
customer.setPid(loginUser.getUserId());
customer.setStatus("0");
save(customer);
@ -106,18 +109,40 @@ public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> i
/**
* 修改客户
* 不是因为寂寞才想你,只是因为想你才寂寞。
*
* @param resources /
* @param customer /
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updateCustomer(Customer resources) throws Exception {
if (resources.getEnabled()) {
resources.setStatus("0");
} else {
resources.setStatus("1");
public void updateCustomer(Customer customer) throws Exception {
UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
if (StringUtils.isNotEmpty(customer.getUserName())) {
userQueryCriteria.setCustomerName(customer.getUserName());
List<Customer> customers = customerMapper.queryCustomers(userQueryCriteria);
if (!customers.isEmpty()) {
throw new BadRequestException("用户名已存在!!!");
}
}
saveOrUpdate(resources);
if (customer.getEnabled()) {
customer.setStatus("0");
} else {
// 强制下线
// StpUtil.logout(customer.getCustomerId());
// StpUtil.kickout(customer.getCustomerId());
customer.setStatus("1");
// 检查目标用户是否有有效的登录状态
if (StpUtil.isLogin(customer.getCustomerId())) {
// 用户已登录,可以执行踢出操作
StpUtil.kickout(customer.getCustomerId());
} else {
// 用户未登录,无法踢出
System.out.println("目标用户未登录,无法执行踢出操作");
}
}
saveOrUpdate(customer);
}

View File

@ -147,19 +147,19 @@ public class DeviceController extends BaseController {
return R.ok();
}
/**
* @param id
* @return
* @ModelAttribute 主要用于将请求参数绑定到 Java 对象上,它会从 HTTP 请求的查询参数Query Parameters
* 或表单数据Form Data中提取值并自动填充到指定的对象属性中。
*/
// @Log("解绑设备")
@Operation(summary = "WEB端解绑设备")
@GetMapping(value = "/unbind")
public R<Void> unbindDevice(@Validated Long id) {
return toAjax(deviceService.webUnBindDevice(id));
}
//
// /**
// * @param id
// * @return
// * @ModelAttribute 主要用于将请求参数绑定到 Java 对象上,它会从 HTTP 请求的查询参数Query Parameters
// * 或表单数据Form Data中提取值并自动填充到指定的对象属性中。
// */
// // @Log("解绑设备")
// @Operation(summary = "WEB端解绑设备")
// @GetMapping(value = "/unbind")
// public R<Void> unbindDevice(@Validated Long id) {
// return toAjax(deviceService.webUnBindDevice(id));
// }
@Operation(summary = "导出数据设备")

View File

@ -0,0 +1,106 @@
package com.fuyuanshen.equipment.controller;
import java.util.List;
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.mybatis.core.page.PageQuery;
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.DeviceLogVo;
import com.fuyuanshen.equipment.domain.bo.DeviceLogBo;
import com.fuyuanshen.equipment.service.IDeviceLogService;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
/**
* 设备日志
*
* @author Lion Li
* @date 2025-07-29
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/equipment/log")
public class DeviceLogController extends BaseController {
private final IDeviceLogService deviceLogService;
/**
* 查询设备日志列表
*/
@SaCheckPermission("equipment:log:list")
@GetMapping("/list")
public TableDataInfo<DeviceLogVo> list(DeviceLogBo bo, PageQuery pageQuery) {
return deviceLogService.queryPageList(bo, pageQuery);
}
/**
* 导出设备日志列表
*/
@SaCheckPermission("equipment:log:export")
@Log(title = "设备日志", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(DeviceLogBo bo, HttpServletResponse response) {
List<DeviceLogVo> list = deviceLogService.queryList(bo);
ExcelUtil.exportExcel(list, "设备日志", DeviceLogVo.class, response);
}
/**
* 获取设备日志详细信息
*
* @param id 主键
*/
@SaCheckPermission("equipment:log:query")
@GetMapping("/{id}")
public R<DeviceLogVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(deviceLogService.queryById(id));
}
/**
* 新增设备日志
*/
@SaCheckPermission("equipment:log:add")
@Log(title = "设备日志", businessType = BusinessType.INSERT)
@RepeatSubmit()
@PostMapping()
public R<Void> add(@Validated(AddGroup.class) @RequestBody DeviceLogBo bo) {
return toAjax(deviceLogService.insertByBo(bo));
}
/**
* 修改设备日志
*/
@SaCheckPermission("equipment:log:edit")
@Log(title = "设备日志", businessType = BusinessType.UPDATE)
@RepeatSubmit()
@PutMapping()
public R<Void> edit(@Validated(EditGroup.class) @RequestBody DeviceLogBo bo) {
return toAjax(deviceLogService.updateByBo(bo));
}
/**
* 删除设备日志
*
* @param ids 主键串
*/
@SaCheckPermission("equipment:log:remove")
@Log(title = "设备日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(deviceLogService.deleteWithValidByIds(List.of(ids), true));
}
}

View File

@ -0,0 +1,105 @@
package com.fuyuanshen.equipment.controller;
import java.util.List;
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.mybatis.core.page.PageQuery;
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.FysEquipmentAlarmRecordVo;
import com.fuyuanshen.equipment.domain.bo.FysEquipmentAlarmRecordBo;
import com.fuyuanshen.equipment.service.IFysEquipmentAlarmRecordService;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
/**
* 设备报警记录
*
* @author Lion Li
* @date 2025-07-29
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/equipment/equipmentAlarmRecord")
public class FysEquipmentAlarmRecordController extends BaseController {
private final IFysEquipmentAlarmRecordService fysEquipmentAlarmRecordService;
/**
* 查询设备报警记录列表
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:list")
@GetMapping("/list")
public TableDataInfo<FysEquipmentAlarmRecordVo> list(FysEquipmentAlarmRecordBo bo, PageQuery pageQuery) {
return fysEquipmentAlarmRecordService.queryPageList(bo, pageQuery);
}
/**
* 导出设备报警记录列表
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:export")
@Log(title = "设备报警记录", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(FysEquipmentAlarmRecordBo bo, HttpServletResponse response) {
List<FysEquipmentAlarmRecordVo> list = fysEquipmentAlarmRecordService.queryList(bo);
ExcelUtil.exportExcel(list, "设备报警记录", FysEquipmentAlarmRecordVo.class, response);
}
/**
* 获取设备报警记录详细信息
*
* @param id 主键
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:query")
@GetMapping("/{id}")
public R<FysEquipmentAlarmRecordVo> getInfo(@NotNull(message = "主键不能为空")
@PathVariable Long id) {
return R.ok(fysEquipmentAlarmRecordService.queryById(id));
}
/**
* 新增设备报警记录
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:add")
@Log(title = "设备报警记录", businessType = BusinessType.INSERT)
@RepeatSubmit()
@PostMapping()
public R<Void> add(@Validated(AddGroup.class) @RequestBody FysEquipmentAlarmRecordBo bo) {
return toAjax(fysEquipmentAlarmRecordService.insertByBo(bo));
}
/**
* 修改设备报警记录
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:edit")
@Log(title = "设备报警记录", businessType = BusinessType.UPDATE)
@RepeatSubmit()
@PutMapping()
public R<Void> edit(@Validated(EditGroup.class) @RequestBody FysEquipmentAlarmRecordBo bo) {
return toAjax(fysEquipmentAlarmRecordService.updateByBo(bo));
}
/**
* 删除设备报警记录
*
* @param ids 主键串
*/
@SaCheckPermission("equipment:equipmentAlarmRecord:remove")
@Log(title = "设备报警记录", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public R<Void> remove(@NotEmpty(message = "主键不能为空")
@PathVariable Long[] ids) {
return toAjax(fysEquipmentAlarmRecordService.deleteWithValidByIds(List.of(ids), true));
}
}

View File

@ -105,7 +105,6 @@ public class Device extends TenantEntity {
@Schema(name = "设备状态")
private Integer deviceStatus;
/**
* 绑定状态
* 0 未绑定
@ -121,7 +120,23 @@ public class Device extends TenantEntity {
private Long bindingUserId;
/**
* 绑定时间
*/
private Date bindingTime;
private String sendMsg;
/**
* 发布主题格式A/{device_id}
* pub_topic
*/
private String pubTopic;
/**
* 订阅主题格式B/{device_id}
* sub_topic
*/
private String subTopic;
}

View File

@ -1,40 +1,51 @@
package com.fuyuanshen.equipment.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fuyuanshen.common.tenant.core.TenantEntity;
import com.baomidou.mybatisplus.annotation.*;
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serial;
/**
* @Description:
* @Author: WY
* @Date: 2025/5/24
**/
* 设备日志对象 device_log
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("device_log")
public class DeviceLog extends TenantEntity {
public class DeviceLog extends BaseEntity {
@TableId(value = "id", type = IdType.AUTO)
// @Schema(value = "ID")
@Serial
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId(value = "id")
private Long id;
// @Schema(value = "设备行为")
/**
* 设备行为
*/
private String deviceAction;
// @Schema(value = "设备名称")
/**
* 设备名称
*/
private String deviceName;
// @Schema(value = "数据来源")
/**
* 数据来源
*/
private String dataSource;
// @Schema(value = "内容")
/**
* 内容
*/
private String content;
public void copy(DeviceLog source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@ -0,0 +1,84 @@
package com.fuyuanshen.equipment.domain;
import com.fuyuanshen.common.tenant.core.TenantEntity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serial;
/**
* 设备报警记录对象 fys_equipment_alarm_record
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("fys_equipment_alarm_record")
public class FysEquipmentAlarmRecord extends TenantEntity {
@Serial
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId(value = "id")
private Long id;
/**
* 报警设备id
*/
private Long deviceId;
/**
* 设备IMEI
*/
private String deviceImei;
/**
* 设备MAC
*/
private String deviceMac;
/**
* 设备名称
*/
private String deviceName;
/**
* 所属代理(客户)
*/
private Long agent;
/**
* 绑定app用户
*/
private Long bindApp;
/**
* 报警类型
*/
private Long alarmType;
/**
* 报警编码
*/
private String alarmCode;
/**
* 报警描述
*/
private String alarmDescription;
/**
* 报警时间
*/
private Date alarmTime;
}

View File

@ -0,0 +1,56 @@
package com.fuyuanshen.equipment.domain.bo;
import com.fuyuanshen.common.core.validate.EditGroup;
import com.fuyuanshen.equipment.domain.DeviceLog;
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import jakarta.validation.constraints.*;
import java.util.List;
/**
* 设备日志业务对象 device_log
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AutoMapper(target = DeviceLog.class, reverseConvertGenerate = false)
public class DeviceLogBo extends BaseEntity {
/**
* ID
*/
@NotNull(message = "ID不能为空", groups = {EditGroup.class})
private Long id;
/**
* 设备编号
*/
private List<Long> deviceIds;
/**
* 设备行为
*/
private String deviceAction;
/**
* 设备名称
*/
private String deviceName;
/**
* 数据来源
*/
private String dataSource;
/**
* 内容
*/
private String content;
}

View File

@ -0,0 +1,82 @@
package com.fuyuanshen.equipment.domain.bo;
import com.fuyuanshen.common.core.validate.EditGroup;
import com.fuyuanshen.equipment.domain.FysEquipmentAlarmRecord;
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import jakarta.validation.constraints.*;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 设备报警记录业务对象 fys_equipment_alarm_record
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AutoMapper(target = FysEquipmentAlarmRecord.class, reverseConvertGenerate = false)
public class FysEquipmentAlarmRecordBo extends BaseEntity {
/**
*
*/
@NotNull(message = "不能为空", groups = { EditGroup.class })
private Long id;
/**
* 报警设备id
*/
private Long deviceId;
/**
* 设备IMEI
*/
private String deviceImei;
/**
* 设备MAC
*/
private String deviceMac;
/**
* 设备名称
*/
private String deviceName;
/**
* 所属代理(客户)
*/
private Long agent;
/**
* 绑定app用户
*/
private Long bindApp;
/**
* 报警类型
*/
private Long alarmType;
/**
* 报警编码
*/
private String alarmCode;
/**
* 报警描述
*/
private String alarmDescription;
/**
* 报警时间
*/
private Date alarmTime;
}

View File

@ -30,5 +30,5 @@ public class AppDeviceBo {
private String sendMsg;
private String deviceId;
private Long deviceId;
}

View File

@ -0,0 +1,16 @@
package com.fuyuanshen.equipment.domain.dto;
import lombok.Data;
import java.util.List;
/**
* 绑定设备参数
*/
@Data
public class AppDeviceSendMsgBo {
private String sendMsg;
private List<Long> deviceIds;
}

View File

@ -1,10 +1,12 @@
package com.fuyuanshen.equipment.domain.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class AppDeviceVo {
public class AppDeviceVo implements Serializable {
private Long id;
@ -39,7 +41,7 @@ public class AppDeviceVo {
private String typeName;
/**
* 蓝牙名称
* 蓝牙名称
*/
private String bluetoothName;
@ -49,4 +51,10 @@ public class AppDeviceVo {
* 1 正常
*/
private Integer deviceStatus;
/**
* 绑定时间
*/
private Date bindingTime;
}

View File

@ -0,0 +1,62 @@
package com.fuyuanshen.equipment.domain.vo;
import com.fuyuanshen.equipment.domain.DeviceLog;
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
import cn.idev.excel.annotation.ExcelProperty;
import com.fuyuanshen.common.excel.annotation.ExcelDictFormat;
import com.fuyuanshen.common.excel.convert.ExcelDictConvert;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* 设备日志视图对象 device_log
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@ExcelIgnoreUnannotated
@AutoMapper(target = DeviceLog.class)
public class DeviceLogVo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* ID
*/
@ExcelProperty(value = "ID")
private Long id;
/**
* 设备行为
*/
@ExcelProperty(value = "设备行为")
private String deviceAction;
/**
* 设备名称
*/
@ExcelProperty(value = "设备名称")
private String deviceName;
/**
* 数据来源
*/
@ExcelProperty(value = "数据来源")
private String dataSource;
/**
* 内容
*/
@ExcelProperty(value = "内容")
private String content;
}

View File

@ -0,0 +1,102 @@
package com.fuyuanshen.equipment.domain.vo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fuyuanshen.equipment.domain.FysEquipmentAlarmRecord;
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
import cn.idev.excel.annotation.ExcelProperty;
import com.fuyuanshen.common.excel.annotation.ExcelDictFormat;
import com.fuyuanshen.common.excel.convert.ExcelDictConvert;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* 设备报警记录视图对象 fys_equipment_alarm_record
*
* @author Lion Li
* @date 2025-07-29
*/
@Data
@ExcelIgnoreUnannotated
@AutoMapper(target = FysEquipmentAlarmRecord.class)
public class FysEquipmentAlarmRecordVo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
*
*/
@ExcelProperty(value = "")
private Long id;
/**
* 报警设备id
*/
@ExcelProperty(value = "报警设备id")
private Long deviceId;
/**
* 设备IMEI
*/
@ExcelProperty(value = "设备IMEI")
private String deviceImei;
/**
* 设备MAC
*/
@ExcelProperty(value = "设备MAC")
private String deviceMac;
/**
* 设备名称
*/
@ExcelProperty(value = "设备名称")
private String deviceName;
/**
* 所属代理(客户)
*/
@ExcelProperty(value = "所属代理", converter = ExcelDictConvert.class)
@ExcelDictFormat(readConverterExp = "客=户")
private Long agent;
/**
* 绑定app用户
*/
@ExcelProperty(value = "绑定app用户")
private Long bindApp;
/**
* 报警类型
*/
@ExcelProperty(value = "报警类型")
private Long alarmType;
/**
* 报警编码
*/
@ExcelProperty(value = "报警编码")
private String alarmCode;
/**
* 报警描述
*/
@ExcelProperty(value = "报警描述")
private String alarmDescription;
/**
* 报警时间
*/
@ExcelProperty(value = "报警时间")
private Date alarmTime;
}

View File

@ -0,0 +1,15 @@
package com.fuyuanshen.equipment.mapper;
import com.fuyuanshen.equipment.domain.DeviceLog;
import com.fuyuanshen.equipment.domain.vo.DeviceLogVo;
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
/**
* 设备日志Mapper接口
*
* @author Lion Li
* @date 2025-07-29
*/
public interface DeviceLogMapper extends BaseMapperPlus<DeviceLog, DeviceLogVo> {
}

View File

@ -0,0 +1,15 @@
package com.fuyuanshen.equipment.mapper;
import com.fuyuanshen.equipment.domain.FysEquipmentAlarmRecord;
import com.fuyuanshen.equipment.domain.vo.FysEquipmentAlarmRecordVo;
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
/**
* 设备报警记录Mapper接口
*
* @author Lion Li
* @date 2025-07-29
*/
public interface FysEquipmentAlarmRecordMapper extends BaseMapperPlus<FysEquipmentAlarmRecord, FysEquipmentAlarmRecordVo> {
}

View File

@ -85,6 +85,14 @@ public interface DeviceService extends IService<Device> {
*/
void unbindDevice(DeviceForm deviceForm);
/**
* WEB端查看APP客户设备绑定
*
* @param bo
* @param pageQuery
* @return
*/
TableDataInfo<AppDeviceVo> queryAppDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery);
int bindDevice(AppDeviceBo bo);
@ -106,4 +114,5 @@ public interface DeviceService extends IService<Device> {
* @return
*/
int webUnBindDevice(Long id);
}

View File

@ -0,0 +1,68 @@
package com.fuyuanshen.equipment.service;
import com.fuyuanshen.equipment.domain.vo.DeviceLogVo;
import com.fuyuanshen.equipment.domain.bo.DeviceLogBo;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import java.util.Collection;
import java.util.List;
/**
* 设备日志Service接口
*
* @author Lion Li
* @date 2025-07-29
*/
public interface IDeviceLogService {
/**
* 查询设备日志
*
* @param id 主键
* @return 设备日志
*/
DeviceLogVo queryById(Long id);
/**
* 分页查询设备日志列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备日志分页列表
*/
TableDataInfo<DeviceLogVo> queryPageList(DeviceLogBo bo, PageQuery pageQuery);
/**
* 查询符合条件的设备日志列表
*
* @param bo 查询条件
* @return 设备日志列表
*/
List<DeviceLogVo> queryList(DeviceLogBo bo);
/**
* 新增设备日志
*
* @param bo 设备日志
* @return 是否新增成功
*/
Boolean insertByBo(DeviceLogBo bo);
/**
* 修改设备日志
*
* @param bo 设备日志
* @return 是否修改成功
*/
Boolean updateByBo(DeviceLogBo bo);
/**
* 校验并批量删除设备日志信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}

View File

@ -0,0 +1,68 @@
package com.fuyuanshen.equipment.service;
import com.fuyuanshen.equipment.domain.vo.FysEquipmentAlarmRecordVo;
import com.fuyuanshen.equipment.domain.bo.FysEquipmentAlarmRecordBo;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import java.util.Collection;
import java.util.List;
/**
* 设备报警记录Service接口
*
* @author Lion Li
* @date 2025-07-29
*/
public interface IFysEquipmentAlarmRecordService {
/**
* 查询设备报警记录
*
* @param id 主键
* @return 设备报警记录
*/
FysEquipmentAlarmRecordVo queryById(Long id);
/**
* 分页查询设备报警记录列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备报警记录分页列表
*/
TableDataInfo<FysEquipmentAlarmRecordVo> queryPageList(FysEquipmentAlarmRecordBo bo, PageQuery pageQuery);
/**
* 查询符合条件的设备报警记录列表
*
* @param bo 查询条件
* @return 设备报警记录列表
*/
List<FysEquipmentAlarmRecordVo> queryList(FysEquipmentAlarmRecordBo bo);
/**
* 新增设备报警记录
*
* @param bo 设备报警记录
* @return 是否新增成功
*/
Boolean insertByBo(FysEquipmentAlarmRecordBo bo);
/**
* 修改设备报警记录
*
* @param bo 设备报警记录
* @return 是否修改成功
*/
Boolean updateByBo(FysEquipmentAlarmRecordBo bo);
/**
* 校验并批量删除设备报警记录信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
}

View File

@ -0,0 +1,157 @@
package com.fuyuanshen.equipment.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.fuyuanshen.equipment.domain.bo.DeviceLogBo;
import com.fuyuanshen.equipment.domain.vo.DeviceLogVo;
import com.fuyuanshen.equipment.domain.DeviceLog;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
import com.fuyuanshen.equipment.service.IDeviceLogService;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;
/**
* 设备日志Service业务层处理
*
* @author Lion Li
* @date 2025-07-29
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class DeviceLogServiceImpl implements IDeviceLogService {
private final DeviceLogMapper baseMapper;
private final DeviceAssignmentsMapper deviceAssignmentsMapper;
/**
* 查询设备日志
*
* @param id 主键
* @return 设备日志
*/
@Override
public DeviceLogVo queryById(Long id) {
return baseMapper.selectVoById(id);
}
/**
* 分页查询设备日志列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备日志分页列表
*/
@Override
public TableDataInfo<DeviceLogVo> queryPageList(DeviceLogBo bo, PageQuery pageQuery) {
LambdaQueryWrapper<DeviceLog> lqw = buildQueryWrapper(bo);
Page<DeviceLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
/**
* 查询符合条件的设备日志列表
*
* @param bo 查询条件
* @return 设备日志列表
*/
@Override
public List<DeviceLogVo> queryList(DeviceLogBo bo) {
LambdaQueryWrapper<DeviceLog> lqw = buildQueryWrapper(bo);
return baseMapper.selectVoList(lqw);
}
private LambdaQueryWrapper<DeviceLog> buildQueryWrapper(DeviceLogBo bo) {
Long userId = LoginHelper.getUserId();
List<DeviceAssignments> assignments = deviceAssignmentsMapper.selectList(new QueryWrapper<DeviceAssignments>().eq("assignee_id", userId));
List<Long> deviceIds = assignments.stream().map(DeviceAssignments::getDeviceId).collect(Collectors.toList());
if (deviceIds.isEmpty()) {
deviceIds.add(-1L);
}
bo.setDeviceIds(deviceIds);
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<DeviceLog> lqw = Wrappers.lambdaQuery();
lqw.orderByDesc(DeviceLog::getCreateTime);
lqw.like(StringUtils.isNotBlank(bo.getDeviceAction()), DeviceLog::getDeviceAction, bo.getDeviceAction());
lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), DeviceLog::getDeviceName, bo.getDeviceName());
lqw.eq(StringUtils.isNotBlank(bo.getDataSource()), DeviceLog::getDataSource, bo.getDataSource());
lqw.like(StringUtils.isNotBlank(bo.getContent()), DeviceLog::getContent, bo.getContent());
lqw.in(CollectionUtil.isNotEmpty(bo.getDeviceIds()), DeviceLog::getDeviceId, bo.getDeviceIds());
return lqw;
}
/**
* 新增设备日志
*
* @param bo 设备日志
* @return 是否新增成功
*/
@Override
public Boolean insertByBo(DeviceLogBo bo) {
DeviceLog add = MapstructUtils.convert(bo, DeviceLog.class);
validEntityBeforeSave(add);
boolean flag = baseMapper.insert(add) > 0;
if (flag) {
bo.setId(add.getId());
}
return flag;
}
/**
* 修改设备日志
*
* @param bo 设备日志
* @return 是否修改成功
*/
@Override
public Boolean updateByBo(DeviceLogBo bo) {
DeviceLog update = MapstructUtils.convert(bo, DeviceLog.class);
validEntityBeforeSave(update);
return baseMapper.updateById(update) > 0;
}
/**
* 保存前的数据校验
*/
private void validEntityBeforeSave(DeviceLog entity) {
// TODO 做一些数据校验,如唯一约束
}
/**
* 校验并批量删除设备日志信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if (isValid) {
// TODO 做一些业务上的校验,判断是否需要校验
}
return baseMapper.deleteByIds(ids) > 0;
}
}

View File

@ -148,6 +148,10 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
@Transactional(rollbackFor = Exception.class)
public void addDevice(DeviceForm deviceForm) throws Exception {
if (deviceForm.getDeviceMac() != null && deviceForm.getBluetoothName() == null) {
throw new BadRequestException("请填写蓝牙名称!!!");
}
Device device1 = deviceMapper.selectOne(new QueryWrapper<Device>().eq("device_mac", deviceForm.getDeviceMac()));
if (device1 != null) {
throw new BadRequestException("设备MAC已存在");
@ -178,6 +182,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
// 转换对象并插入数据库
Device device = new Device();
BeanUtil.copyProperties(deviceForm, device, true);
device.setDeviceNo(createDeviceNo());
LoginUser loginUser = LoginHelper.getLoginUser();
@ -186,7 +191,12 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
device.setCreateByName(loginUser.getNickname());
device.setTypeName(deviceTypes.getTypeName());
device.setDeviceType(deviceTypes.getId());
if (device.getDeviceImei() != null) {
device.setPubTopic("A/" + device.getDeviceImei());
device.setSubTopic("B/" + device.getDeviceImei());
}
// 0 未绑定
device.setBindingStatus(0);
deviceMapper.insert(device);
// 新增设备类型记录
@ -293,17 +303,26 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
for (Long id : ids) {
DeviceAssignments deviceAssignment = deviceAssignmentsMapper.selectById(id);
Device deviceType = deviceMapper.selectById(deviceAssignment.getDeviceId());
Device device = deviceMapper.selectById(deviceAssignment.getDeviceId());
if (StringUtils.isNotEmpty(deviceAssignment.getAssigneeName())) {
throw new BadRequestException(deviceType.getDeviceName() + ":设备已分配,请先解绑设备!!!");
throw new BadRequestException(device.getDeviceName() + ":设备已分配,请先解绑设备!!!");
}
if (device.getBindingStatus() != null && device.getBindingStatus().equals(1)) {
throw new BadRequestException(device.getDeviceName() + ":设备已绑定,请先解绑设备!!!");
}
// 接收者
if (Objects.equals(deviceAssignment.getAssigneeId(), deviceType.getOriginalOwnerId())) {
if (Objects.equals(deviceAssignment.getAssigneeId(), device.getOriginalOwnerId())) {
invalidIds.add(deviceAssignment.getDeviceId());
}
// 删除设备:分配记录
deviceAssignmentsMapper.delete(new LambdaQueryWrapper<DeviceAssignments>()
.eq(DeviceAssignments::getDeviceId, deviceAssignment.getDeviceId())
.eq(DeviceAssignments::getAssigneeId, deviceAssignment.getAssigneeId()));
}
deviceAssignmentsMapper.deleteByIds(ids);
@ -470,7 +489,13 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
}
/**
* WEB端查看APP客户设备绑定
*
* @param bo
* @param pageQuery
* @return
*/
@Override
public TableDataInfo<AppDeviceVo> queryAppDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery) {
if (bo.getBindingUserId() == null) {

View File

@ -107,6 +107,13 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DeviceType resources) {
// 校验设备类型名称
List<DeviceType> typeName = deviceTypeMapper.selectList(new QueryWrapper<DeviceType>().eq("type_name", resources.getTypeName()));
if (CollectionUtil.isNotEmpty(typeName)) {
throw new RuntimeException("设备类型名称已存在,无法新增!!!");
}
LoginUser loginUser = LoginHelper.getLoginUser();
resources.setCustomerId(loginUser.getUserId());
resources.setOwnerCustomerId(loginUser.getUserId());
@ -141,11 +148,23 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
if (deviceType == null) {
throw new RuntimeException("设备类型不存在");
}
List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>()
.eq("device_type", deviceTypeGrants.getDeviceTypeId()));
if (CollectionUtil.isNotEmpty(devices)) {
throw new RuntimeException("该设备类型已绑定设备,无法修改!!!");
}
// 校验设备类型名称
DeviceType dt = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("type_name", resources.getTypeName()));
if (dt != null && !dt.getId().equals(deviceType.getId())) {
throw new RuntimeException("设备类型名称已存在,无法修改!!!");
}
if (!Objects.equals(deviceType.getCustomerId(), LoginHelper.getUserId())) {
throw new RuntimeException("无权修改该设备类型");
}
// if (deviceMapper.countByTypeId(resources.getId()) > 0)
// throw new RuntimeException("该设备类型已被使用,无法删除");
BeanUtil.copyProperties(resources, deviceType);
deviceTypeMapper.updateById(deviceType);
}
@ -179,7 +198,7 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>()
.eq("device_type", deviceTypeGrant.getDeviceTypeId()));
if (CollectionUtil.isNotEmpty(devices)) {
throw new RuntimeException("该设备类型已绑定设备,无法删除");
throw new RuntimeException("该设备类型已绑定设备,无法删除");
}
deviceTypeId.add(deviceTypeGrant.getDeviceTypeId());
}

View File

@ -0,0 +1,141 @@
package com.fuyuanshen.equipment.service.impl;
import com.fuyuanshen.common.core.utils.MapstructUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.fuyuanshen.equipment.domain.bo.FysEquipmentAlarmRecordBo;
import com.fuyuanshen.equipment.domain.vo.FysEquipmentAlarmRecordVo;
import com.fuyuanshen.equipment.domain.FysEquipmentAlarmRecord;
import com.fuyuanshen.equipment.mapper.FysEquipmentAlarmRecordMapper;
import com.fuyuanshen.equipment.service.IFysEquipmentAlarmRecordService;
import java.util.List;
import java.util.Map;
import java.util.Collection;
/**
* 设备报警记录Service业务层处理
*
* @author Lion Li
* @date 2025-07-29
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class FysEquipmentAlarmRecordServiceImpl implements IFysEquipmentAlarmRecordService {
private final FysEquipmentAlarmRecordMapper baseMapper;
/**
* 查询设备报警记录
*
* @param id 主键
* @return 设备报警记录
*/
@Override
public FysEquipmentAlarmRecordVo queryById(Long id){
return baseMapper.selectVoById(id);
}
/**
* 分页查询设备报警记录列表
*
* @param bo 查询条件
* @param pageQuery 分页参数
* @return 设备报警记录分页列表
*/
@Override
public TableDataInfo<FysEquipmentAlarmRecordVo> queryPageList(FysEquipmentAlarmRecordBo bo, PageQuery pageQuery) {
LambdaQueryWrapper<FysEquipmentAlarmRecord> lqw = buildQueryWrapper(bo);
Page<FysEquipmentAlarmRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
return TableDataInfo.build(result);
}
/**
* 查询符合条件的设备报警记录列表
*
* @param bo 查询条件
* @return 设备报警记录列表
*/
@Override
public List<FysEquipmentAlarmRecordVo> queryList(FysEquipmentAlarmRecordBo bo) {
LambdaQueryWrapper<FysEquipmentAlarmRecord> lqw = buildQueryWrapper(bo);
return baseMapper.selectVoList(lqw);
}
private LambdaQueryWrapper<FysEquipmentAlarmRecord> buildQueryWrapper(FysEquipmentAlarmRecordBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<FysEquipmentAlarmRecord> lqw = Wrappers.lambdaQuery();
lqw.orderByAsc(FysEquipmentAlarmRecord::getId);
lqw.eq(bo.getDeviceId() != null, FysEquipmentAlarmRecord::getDeviceId, bo.getDeviceId());
lqw.eq(StringUtils.isNotBlank(bo.getDeviceImei()), FysEquipmentAlarmRecord::getDeviceImei, bo.getDeviceImei());
lqw.eq(StringUtils.isNotBlank(bo.getDeviceMac()), FysEquipmentAlarmRecord::getDeviceMac, bo.getDeviceMac());
lqw.like(StringUtils.isNotBlank(bo.getDeviceName()), FysEquipmentAlarmRecord::getDeviceName, bo.getDeviceName());
lqw.eq(bo.getAgent() != null, FysEquipmentAlarmRecord::getAgent, bo.getAgent());
lqw.eq(bo.getBindApp() != null, FysEquipmentAlarmRecord::getBindApp, bo.getBindApp());
lqw.eq(bo.getAlarmType() != null, FysEquipmentAlarmRecord::getAlarmType, bo.getAlarmType());
lqw.eq(StringUtils.isNotBlank(bo.getAlarmCode()), FysEquipmentAlarmRecord::getAlarmCode, bo.getAlarmCode());
lqw.eq(StringUtils.isNotBlank(bo.getAlarmDescription()), FysEquipmentAlarmRecord::getAlarmDescription, bo.getAlarmDescription());
lqw.eq(bo.getAlarmTime() != null, FysEquipmentAlarmRecord::getAlarmTime, bo.getAlarmTime());
return lqw;
}
/**
* 新增设备报警记录
*
* @param bo 设备报警记录
* @return 是否新增成功
*/
@Override
public Boolean insertByBo(FysEquipmentAlarmRecordBo bo) {
FysEquipmentAlarmRecord add = MapstructUtils.convert(bo, FysEquipmentAlarmRecord.class);
validEntityBeforeSave(add);
boolean flag = baseMapper.insert(add) > 0;
if (flag) {
bo.setId(add.getId());
}
return flag;
}
/**
* 修改设备报警记录
*
* @param bo 设备报警记录
* @return 是否修改成功
*/
@Override
public Boolean updateByBo(FysEquipmentAlarmRecordBo bo) {
FysEquipmentAlarmRecord update = MapstructUtils.convert(bo, FysEquipmentAlarmRecord.class);
validEntityBeforeSave(update);
return baseMapper.updateById(update) > 0;
}
/**
* 保存前的数据校验
*/
private void validEntityBeforeSave(FysEquipmentAlarmRecord entity){
//TODO 做一些数据校验,如唯一约束
}
/**
* 校验并批量删除设备报警记录信息
*
* @param ids 待删除的主键集合
* @param isValid 是否进行有效性校验
* @return 是否删除成功
*/
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
if(isValid){
//TODO 做一些业务上的校验,判断是否需要校验
}
return baseMapper.deleteByIds(ids) > 0;
}
}

View File

@ -0,0 +1,362 @@
//package com.fuyuanshen.equipment.utils.c;
//
//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);
// }
//
// private 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,204 @@
package com.fuyuanshen.equipment.utils.c;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;
public class DotMatrixDisplaySimulator extends JFrame {
private static final int WIDTH = 160;
private static final int HEIGHT = 80;
private static final int SCALE = 4; // 显示缩放比例
private JComboBox<Integer> fontSizeCombo;
private JComboBox<String> exampleCombo;
private JTextArea textInput;
private DotMatrixPanel displayPanel;
private final String[] examples = {
"紧急通知:现场危险,请立即撤离!",
"警告:高温区域,禁止入内!",
"系统故障:请立即联系技术人员处理",
"安全提示:请佩戴防护装备进入作业区",
"欢迎使用点阵显示屏模拟系统",
"现场危险,停止救援,紧急撤离至安全区域!"
};
public DotMatrixDisplaySimulator() {
super("160x80点阵显示屏模拟器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLayout(new BorderLayout());
// 创建控制面板
JPanel controlPanel = new JPanel(new GridLayout(1, 4, 10, 10));
controlPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 字体大小选择
controlPanel.add(new JLabel("字体大小:"));
fontSizeCombo = new JComboBox<>(new Integer[]{8, 10, 12, 14, 16, 18, 20, 24});
fontSizeCombo.setSelectedItem(14);
controlPanel.add(fontSizeCombo);
// 示例选择
controlPanel.add(new JLabel("示例文本:"));
exampleCombo = new JComboBox<>(examples);
exampleCombo.addActionListener(e -> textInput.setText(examples[exampleCombo.getSelectedIndex()]));
controlPanel.add(exampleCombo);
// 文本输入
textInput = new JTextArea(examples[0]);
textInput.setLineWrap(true);
textInput.setWrapStyleWord(true);
JScrollPane textScroll = new JScrollPane(textInput);
textScroll.setBorder(BorderFactory.createTitledBorder("输入文本"));
// 点阵显示面板
displayPanel = new DotMatrixPanel();
// 添加组件
add(controlPanel, BorderLayout.NORTH);
add(textScroll, BorderLayout.CENTER);
add(displayPanel, BorderLayout.SOUTH);
// 添加事件监听器
fontSizeCombo.addActionListener(e -> displayPanel.repaint());
textInput.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
public void changedUpdate(javax.swing.event.DocumentEvent e) { update(); }
public void removeUpdate(javax.swing.event.DocumentEvent e) { update(); }
public void insertUpdate(javax.swing.event.DocumentEvent e) { update(); }
private void update() {
displayPanel.repaint();
}
});
setLocationRelativeTo(null);
}
class DotMatrixPanel extends JPanel {
private final int panelWidth = WIDTH * SCALE;
private final int panelHeight = HEIGHT * SCALE;
public DotMatrixPanel() {
setPreferredSize(new Dimension(panelWidth, panelHeight + 50));
setBorder(BorderFactory.createTitledBorder("点阵预览 (160x80)"));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制点阵背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, panelWidth, panelHeight);
// 绘制网格
g.setColor(new Color(240, 240, 240));
for (int x = 0; x <= WIDTH; x++) {
int xPos = x * SCALE;
g.drawLine(xPos, 0, xPos, panelHeight);
}
for (int y = 0; y <= HEIGHT; y++) {
int yPos = y * SCALE;
g.drawLine(0, yPos, panelWidth, yPos);
}
// 绘制文本
String text = textInput.getText();
int fontSize = (Integer) fontSizeCombo.getSelectedItem();
Font font = new Font("黑体", Font.PLAIN, fontSize);
// 创建虚拟点阵图像
BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D imgG = img.createGraphics();
imgG.setColor(Color.WHITE);
imgG.fillRect(0, 0, WIDTH, HEIGHT);
imgG.setColor(Color.BLACK);
imgG.setFont(font);
imgG.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 绘制文本到虚拟点阵
FontMetrics metrics = imgG.getFontMetrics();
int lineHeight = metrics.getHeight();
int yPos = metrics.getAscent();
String[] lines = text.split("\n");
int maxLines = HEIGHT / lineHeight;
int actualLines = Math.min(lines.length, maxLines);
int totalChars = 0;
for (int i = 0; i < actualLines; i++) {
String line = lines[i];
int lineWidth = metrics.stringWidth(line);
int maxChars = WIDTH / metrics.stringWidth(""); // 估算每行字数
// 截断超过宽度的文本
if (lineWidth > WIDTH) {
while (metrics.stringWidth(line) > WIDTH) {
line = line.substring(0, line.length() - 1);
}
line += "...";
}
// 居中显示文本
int xPos = (WIDTH - metrics.stringWidth(line)) / 2;
imgG.drawString(line, xPos, yPos);
totalChars += line.length();
yPos += lineHeight;
if (yPos + lineHeight > HEIGHT) break;
}
imgG.dispose();
// 绘制到预览面板
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int rgb = img.getRGB(x, y) & 0xFFFFFF;
if (rgb != 0xFFFFFF) { // 黑色像素
g.setColor(Color.BLACK);
g.fillRect(x * SCALE, y * SCALE, SCALE, SCALE);
}
}
}
// 显示统计信息
g.setColor(Color.BLACK);
g.setFont(new Font("宋体", Font.PLAIN, 12));
String info = String.format("字体大小: %dpt | 显示行数: %d/%d | 显示字数: %d",
fontSize, actualLines, maxLines, totalChars);
g.drawString(info, 10, panelHeight + 20);
String capacity = String.format("容量分析: %d×80点阵可显示%d-%d个汉字%dpt字体",
WIDTH,
(int)(WIDTH*HEIGHT/(fontSize*fontSize*1.2)),
(int)(WIDTH*HEIGHT/(fontSize*fontSize*0.8)),
fontSize);
g.drawString(capacity, 10, panelHeight + 35);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DotMatrixDisplaySimulator frame = new DotMatrixDisplaySimulator();
frame.setVisible(true);
// 显示使用提示
String message = "<html><div style='text-align:center;'><b>160×80点阵显示屏文字容量分析</b><br><br>"
+ "• 使用上方下拉菜单选择字体大小和示例文本<br>"
+ "• 在文本区域输入自定义内容<br>"
+ "• 点阵预览区域实时显示效果<br><br>"
+ "<b>容量参考:</b><br>"
+ "8-9pt约20字/行 × 10行 = 200字<br>"
+ "10-11pt约16字/行 × 8行 = 128字<br>"
+ "12-13pt约13字/行 × 6行 = 78字<br>"
+ "14-15pt约11字/行 × 5行 = 55字<br>"
+ "16-18pt约9字/行 × 4行 = 36字<br>"
+ "20-24pt约7字/行 × 3行 = 21字</div></html>";
JOptionPane.showMessageDialog(frame, message, "使用说明", JOptionPane.INFORMATION_MESSAGE);
});
}
}

View File

@ -0,0 +1,310 @@
//package com.fuyuanshen.equipment.utils.c;
//
//import com.fuyuanshen.common.redis.utils.RedisUtils;
//
//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\\6170_强光_160_80_2.jpg", 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));
//// }
//
// RedisUtils.setCacheObject("app_logo_data", largeData);
//
// // 示例:获取特定块的数据
// 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;
// }
// /**
// * 打印分块信息
// *
// * @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];
// }
// }
//}

View File

@ -7,6 +7,7 @@ import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@ -23,6 +24,11 @@ public class ReliableTextToBitmap {
String name = "12李34四56";
byte[] unitBytes = textToBitmapBytes(unit);
for (int i = 0; i < unitBytes.length; i++) {
//打印byte转十进制
System.out.printf("0x%02X", unitBytes[i]);
}
// System.out.println("单元数据: "+Arrays.toString(unitBytes));
byte[] deptBytes = textToBitmapBytes(department);
byte[] nameBytes = textToBitmapBytes(name);

View File

@ -0,0 +1,185 @@
package com.fuyuanshen.equipment.utils.c;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TextToDotMatrix {
public static void main(String[] args) {
String text = "现场危险,停止救援,\n紧急撤离至安全区域";
int width = 160; // 点阵宽度
int height = 80; // 点阵高度
try {
// 1. 创建点阵图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = image.createGraphics();
// 设置背景为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 设置字体并居中显示文本
g.setColor(Color.BLACK);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 自动调整字体大小以适应区域
Font font = findBestFitFont(text, width, height, g);
g.setFont(font);
// 计算文本位置并绘制
drawCenteredText(g, text, width, height);
g.dispose();
// 2. 生成二进制数组
List<Byte> byteList = new ArrayList<>();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x += 8) {
byte b = 0;
for (int bit = 0; bit < 8; bit++) {
int xPos = x + bit;
if (xPos < width) {
int rgb = image.getRGB(xPos, y) & 0xFFFFFF;
if (rgb != 0xFFFFFF) { // 黑色像素
b |= (1 << (7 - bit));
}
}
}
byteList.add(b);
}
}
// 转换为字节数组
byte[] dotMatrixData = new byte[byteList.size()];
for (int i = 0; i < byteList.size(); i++) {
dotMatrixData[i] = byteList.get(i);
}
// 3. 保存预览图片
ImageIO.write(image, "png", new File("warning_display.png"));
System.out.println("预览图片已生成: warning_display.png");
// 4. 打印点阵数据信息
System.out.println("\n点阵数据信息:");
System.out.println("尺寸: " + width + "x" + height + " 像素");
System.out.println("数据大小: " + dotMatrixData.length + " 字节");
System.out.println("每行字节数: " + (width / 8));
System.out.println("总行数: " + height);
// 5. 打印二进制数组(十六进制格式)
System.out.println("\n点阵数据字节数组 (HEX):");
System.out.print("byte[] dotMatrixData = {");
for (int i = 0; i < dotMatrixData.length; i++) {
System.out.printf("0x%02X", dotMatrixData[i] & 0xFF);
if (i < dotMatrixData.length - 1) System.out.print(", ");
if (i % 16 == 15) System.out.println();
}
System.out.println("};\n");
// 6. 打印点阵图预览
System.out.println("点阵图预览 (缩小版):");
printTextPreview(image);
} catch (IOException e) {
e.printStackTrace();
}
}
// 自动寻找最佳字体大小
private static Font findBestFitFont(String text, int width, int height, Graphics2D g) {
int fontSize = 20; // 初始字体大小
Font bestFont = null;
int bestHeight = 0;
while (fontSize > 8) {
Font font = new Font("黑体", Font.BOLD, fontSize);
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
// 计算文本所需高度
String[] lines = text.split("\n");
int textHeight = metrics.getHeight() * lines.length;
// 检查是否超出高度
if (textHeight < height * 0.8) {
bestFont = font;
bestHeight = textHeight;
break;
}
fontSize--;
}
// 如果没有找到合适字体,使用最小字体
if (bestFont == null) {
bestFont = new Font("黑体", Font.BOLD, 8);
}
System.out.println("使用字体: " + bestFont.getSize() + "pt");
return bestFont;
}
// 居中绘制文本
private static void drawCenteredText(Graphics g, String text, int width, int height) {
FontMetrics metrics = g.getFontMetrics();
String[] lines = text.split("\n");
// 计算总文本高度
int totalHeight = metrics.getHeight() * lines.length;
// 计算起始Y位置
int y = (height - totalHeight) / 2 + metrics.getAscent();
for (String line : lines) {
// 计算X位置使文本居中
int x = (width - metrics.stringWidth(line)) / 2;
g.drawString(line, x, y);
y += metrics.getHeight();
}
}
// 打印文本预览
private static void printTextPreview(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
// 缩小预览比例
int scale = 4;
int previewWidth = width / scale;
int previewHeight = height / scale;
for (int y = 0; y < previewHeight; y++) {
for (int x = 0; x < previewWidth; x++) {
int pixelCount = 0;
for (int dy = 0; dy < scale; dy++) {
for (int dx = 0; dx < scale; dx++) {
int origX = x * scale + dx;
int origY = y * scale + dy;
if (origX < width && origY < height) {
int rgb = image.getRGB(origX, origY) & 0xFFFFFF;
if (rgb != 0xFFFFFF) { // 黑色像素
pixelCount++;
}
}
}
}
// 根据黑色像素密度选择字符
if (pixelCount > scale * scale * 0.7) {
System.out.print("██");
} else if (pixelCount > scale * scale * 0.4) {
System.out.print("▓▓");
} else if (pixelCount > scale * scale * 0.1) {
System.out.print("░░");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

View File

@ -0,0 +1,78 @@
package com.fuyuanshen.equipment.utils.map;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
/**
* @author: 默苍璃
* @date: 2025-07-2615:59
*/
@Data
public class GetAddressFromLatUtil {
private final static Logger logger = LoggerFactory.getLogger(GetAddressFromLatUtil.class);
public static void main(String[] args) {
double[] doubles = LngLonUtil.gps84_To_Gcj02(22.6826096, 113.986969);
System.out.println(doubles[0]);
System.out.println(doubles[1]);
// lat 31.2990170 纬度 39.909 116.40,39.92 113.39039,23.131798 113.97556991,22.67075292
// log 121.3466440 经度 116.39742 113.9751543,22.5603342
String add = GetAddressFromLatUtil.getAdd(String.valueOf(doubles[1]), String.valueOf(doubles[0]));
logger.info(add);
// System.out.println(System.currentTimeMillis());
}
/**
* 根据经纬度获取省市区
*
* @param log
* @param lat
* @return
*/
public static String getAdd(String log, String lat) {
// lat 小 log 大
// 注意key是在高德/百度开放平台申请的key,高德地图具体获得key的步骤请查看网址:https://developer.amap.com/api/webservice/guide/create-project/get-key
// 百度地图开放平台的网址https://lbsyun.baidu.com/index.php 在该平台注册即可
String key = "84a12a692ae378effdf741e16d584cd3";
// 地理编码 详细中文地址转为经纬度信息 请求地址: https://restapi.amap.com/v3/geocode/geo?parameters
// 地理逆编码:经纬度信息转中文地址信息 请求地址https://restapi.amap.com/v3/geocode/regeo?parameters
// 第一个是高德的逆地理编码 第二个是百度的逆地理编码 均为get请求
String urlString = "https://restapi.amap.com/v3/geocode/regeo?location=" + log + "," + lat + "&extensions=base&batch=false&roadlevel=0&key=" + key;
// String urlString = "https://api.map.baidu.com/reverse_geocoding/v3/?ak="+key+"&output=json&coordtype=wgs84ll&location="+lat+","+log;
String res = "";
try {
URL url = new URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
// 解析结果
JSONObject jsonObject = JSONObject.parseObject(res);
logger.info(jsonObject.toJSONString());
// 这个是高德的
JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
// 这个是百度的
// JSONObject jsonObject1 = jsonObject.getJSONObject("result");
res = jsonObject1.getString("formatted_address");
} catch (Exception e) {
logger.error("获取地址信息异常{}", e.getMessage());
return null;
}
System.out.println("通过API获取到具体位置:" + res);
return res;
}
}

View File

@ -0,0 +1,170 @@
package com.fuyuanshen.equipment.utils.map;
/**
* @author: 默苍璃
* @date: 2025-07-2616:25
*/
public class LngLonUtil {
public static double pi = 3.1415926535897932384626;
public static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
public static double a = 6378245.0;
public static double ee = 0.00669342162296594323;
public static double transformLat(double x, double y) {
double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
return ret;
}
public static double transformLon(double x, double y) {
double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
return ret;
}
public static double[] transform(double lat, double lon) {
if (outOfChina(lat, lon)) {
return new double[]{lat, lon};
}
double dLat = transformLat(lon - 105.0, lat - 35.0);
double dLon = transformLon(lon - 105.0, lat - 35.0);
double radLat = lat / 180.0 * pi;
double magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
double mgLat = lat + dLat;
double mgLon = lon + dLon;
return new double[]{mgLat, mgLon};
}
/**
* 判断是否在中国
*
* @param lat
* @param lon
* @return
*/
public static boolean outOfChina(double lat, double lon) {
if (lon < 72.004 || lon > 137.8347)
return true;
if (lat < 0.8293 || lat > 55.8271)
return true;
return false;
}
/**
* 84 ==》 高德
*
* @param lat
* @param lon
* @return
*/
public static double[] gps84_To_Gcj02(double lat, double lon) {
if (outOfChina(lat, lon)) {
return new double[]{lat, lon};
}
double dLat = transformLat(lon - 105.0, lat - 35.0);
double dLon = transformLon(lon - 105.0, lat - 35.0);
double radLat = lat / 180.0 * pi;
double magic = Math.sin(radLat);
magic = 1 - ee * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
double mgLat = lat + dLat;
double mgLon = lon + dLon;
return new double[]{mgLat, mgLon};
}
/**
* 高德 ==》 84
*
* @param lon * @param lat * @return
*/
public static double[] gcj02_To_Gps84(double lat, double lon) {
double[] gps = transform(lat, lon);
double lontitude = lon * 2 - gps[1];
double latitude = lat * 2 - gps[0];
return new double[]{latitude, lontitude};
}
/**
* 高德 == 》 百度
*
* @param lat
* @param lon
*/
public static double[] gcj02_To_Bd09(double lat, double lon) {
double x = lon, y = lat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
double tempLon = z * Math.cos(theta) + 0.0065;
double tempLat = z * Math.sin(theta) + 0.006;
double[] gps = {tempLat, tempLon};
return gps;
}
/**
* 百度 == 》 高德
*
* @param lat
* @param lon
*/
public static double[] bd09_To_Gcj02(double lat, double lon) {
double x = lon - 0.0065, y = lat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
double tempLon = z * Math.cos(theta);
double tempLat = z * Math.sin(theta);
double[] gps = {tempLat, tempLon};
return gps;
}
/**
* 84 == 》 百度
*
* @param lat
* @param lon
* @return
*/
public static double[] gps84_To_bd09(double lat, double lon) {
double[] gcj02 = gps84_To_Gcj02(lat, lon);
double[] bd09 = gcj02_To_Bd09(gcj02[0], gcj02[1]);
return bd09;
}
/**
* 百度 == 》 84
*
* @param lat
* @param lon
* @return
*/
public static double[] bd09_To_gps84(double lat, double lon) {
double[] gcj02 = bd09_To_Gcj02(lat, lon);
double[] gps84 = gcj02_To_Gps84(gcj02[0], gcj02[1]);
// 保留小数点后六位
gps84[0] = retain6(gps84[0]);
gps84[1] = retain6(gps84[1]);
return gps84;
}
/*
* 保留小数点后六位
* @param num
* @return
*/
private static double retain6(double num) {
String result = String.format("%.6f", num);
return Double.valueOf(result);
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fuyuanshen.equipment.mapper.DeviceLogMapper">
</mapper>

View File

@ -38,13 +38,19 @@
<!-- 分页查询设备 -->
<select id="findAll" resultType="com.fuyuanshen.equipment.domain.Device">
select
da.id AS id,d.device_name,d.bluetooth_name,
d.device_pic, d.device_mac, d.device_sn, d.update_by,d.device_imei,
d.update_time, dg.id AS device_type, d.remark, d.binding_status,t.type_name AS typeName,
da.assignee_id AS customerId, da.assignee_name AS customerName, da.active AS deviceStatus,
da.create_time AS create_time , da.assigner_name AS createByName , da.id AS assignId
from device d
SELECT *
FROM (
SELECT
da.id AS id, d.device_name, d.bluetooth_name,
d.pub_topic, d.sub_topic, d.device_pic,
d.device_mac, d.device_sn, d.update_by,
d.device_imei, d.update_time, dg.id AS device_type,
d.remark, d.binding_status, t.type_name AS typeName,
da.assignee_id AS customerId, da.assignee_name AS customerName,
da.active AS deviceStatus, da.create_time AS create_time,
da.assigner_name AS createByName, da.id AS assignId,
ROW_NUMBER() OVER (PARTITION BY d.id ORDER BY da.create_time DESC) AS rn
FROM device d
LEFT JOIN device_type t ON d.device_type = t.id
LEFT JOIN device_type_grants dg ON dg.device_type_id = t.id
LEFT JOIN device_assignments da ON da.device_id = d.id
@ -71,9 +77,12 @@
AND da.assignee_id = #{criteria.currentOwnerId}
AND dg.customer_id = #{criteria.currentOwnerId}
</where>
ORDER BY da.create_time DESC
) AS ranked
WHERE rn = 1
ORDER BY create_time DESC
</select>
<select id="findAllDevices" resultType="com.fuyuanshen.equipment.domain.Device">
select
d.id, d.customer_id, d.device_name,d.bluetooth_name,
@ -138,10 +147,12 @@
d.device_pic,
dt.type_name,
dt.communication_mode,
d.bluetooth_name
d.bluetooth_name,
c.binding_time
from device d
inner join device_type dt on d.device_type = dt.id
where d.binding_user_id = #{criteria.bindingUserId}
inner join app_device_bind_record c on d.id = c.device_id
where c.binding_user_id = #{criteria.bindingUserId}
<if test="criteria.deviceType != null">
and d.device_type = #{criteria.deviceType}
</if>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fuyuanshen.equipment.mapper.FysEquipmentAlarmRecordMapper">
</mapper>

View File

@ -1,31 +0,0 @@
package com.fuyuanshen.system.mqtt.receiver;
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.Service;
import java.util.Objects;
/**
* @Author: HarryLin
* @Date: 2025/3/20 15:24
* @Company: 北京红山信息科技研究院有限公司
* @Email: linyun@***.com.cn
**/
@Service
@Slf4j
public class ReceiverMessageHandler implements MessageHandler {
@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);
}
}

12
pom.xml
View File

@ -83,6 +83,10 @@
<monitor.username>fys</monitor.username>
<monitor.password>123456</monitor.password>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
@ -93,10 +97,10 @@
<monitor.username>fys</monitor.username>
<monitor.password>123456</monitor.password>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
<!-- <activation> -->
<!-- &lt;!&ndash; 默认环境 &ndash;&gt; -->
<!-- <activeByDefault>true</activeByDefault> -->
<!-- </activation> -->
<!-- <activation> -->
<!-- &lt;!&ndash; 默认环境 &ndash;&gt; -->
<!-- <activeByDefault>true</activeByDefault> -->