1
0

Merge remote-tracking branch 'upstream/dyf-device' into main-dyf

This commit is contained in:
2025-08-25 14:32:19 +08:00
36 changed files with 1673 additions and 293 deletions

View File

@ -0,0 +1,96 @@
package com.fuyuanshen.app.controller.device;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.web.service.device.DeviceBJQBizService;
import com.fuyuanshen.web.service.device.DeviceXinghanBizService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* HBY670设备控制类
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/xinghan/device")
public class AppDeviceXinghanController extends BaseController {
private final DeviceXinghanBizService appDeviceService;
/**
* 人员信息登记
*/
@PostMapping(value = "/registerPersonInfo")
// @FunctionAccessAnnotation("registerPersonInfo")
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
return toAjax(appDeviceService.registerPersonInfo(bo));
}
/**
* 上传设备logo图片
*/
@PostMapping("/uploadLogo")
@FunctionAccessAnnotation("uploadLogo")
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
MultipartFile file = bo.getFile();
if(file.getSize()>1024*1024*2){
return R.warn("图片不能大于2M");
}
appDeviceService.uploadDeviceLogo(bo);
return R.ok();
}
/**
* 静电预警档位
* 3,2,1,0,分别表示高档/中档/低挡/关闭
*/
@PostMapping("/DetectGradeSettings")
public R<Void> DetectGradeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.upDetectGradeSettings(params);
return R.ok();
}
/**
* 照明档位
* 照明档位2,1,0,分别表示弱光/强光/关闭
*/
@PostMapping("/LightGradeSettings")
public R<Void> LightGradeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.upLightGradeSettings(params);
return R.ok();
}
/**
* SOS档位
* SOS档位2,1,0, 分别表示红蓝模式/爆闪模式/关闭
*/
@PostMapping("/SOSGradeSettings")
public R<Void> SOSGradeSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.upSOSGradeSettings(params);
return R.ok();
}
/**
* 静止报警状态
* 静止报警状态0-未静止报警1-正在静止报警。
*/
@PostMapping("/ShakeBitSettings")
public R<Void> ShakeBitSettings(@RequestBody DeviceInstructDto params) {
// params 转 JSONObject
appDeviceService.upShakeBitSettings(params);
return R.ok();
}
}

View File

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

View File

@ -14,4 +14,5 @@ public class AppDeviceLogoUploadDto {
*/
private MultipartFile file;
private Integer chunkSize;
}

View File

@ -13,8 +13,17 @@ public final class MqttXinghanCommandType {
private MqttXinghanCommandType() {}
public enum XinghanCommandTypeEnum {
/**
* 星汉设备主动上报数据
*/
GRADE_INFO(101),
/**
* 星汉开机LOGO
*/
PIC_TRANS(102),
/**
* 星汉设备发送消息 (XingHan send msg)
*/
TEX_TRANS(103),
BREAK_NEWS(104),
UNKNOWN(0);

View File

@ -20,37 +20,37 @@ public class MqttXinghanJson {
* 第三键值对SOS档位2,1,0, 分别表示红蓝模式/爆闪模式/关闭
*/
@JsonProperty("sta_SOSGrade")
public int staSOSGrade;
public Integer staSOSGrade;
/**
* 第四键值对剩余照明时间0-5999单位分钟。
*/
@JsonProperty("sta_PowerTime")
public int staPowerTime;
public Integer staPowerTime;
/**
* 第五键值对剩余电量百分比0-100
*/
@JsonProperty("sta_PowerPercent")
public int staPowerPercent;
public Integer staPowerPercent;
/**
* 第六键值对, 近电预警级别, 0-无预警1-弱预警2-中预警3-强预警4-非常强预警。
*/
@JsonProperty("sta_DetectResult")
public int staDetectResult;
public Integer staDetectResult;
/**
* 第七键值对, 静止报警状态0-未静止报警1-正在静止报警。
*/
@JsonProperty("staShakeBit")
public int sta_ShakeBit;
public Integer sta_ShakeBit;
/**
* 第八键值对, 4G信号强度0-32数值越大信号越强。
*/
@JsonProperty("sta_4gSinal")
public int sta4gSinal;
public Integer sta4gSinal;
/**
* 第九键值对IMIE卡号
*/
@JsonProperty("sta_imei")
public int staimei;
public String staimei;
/**
* 第十键值对,经度
*/

View File

@ -13,4 +13,8 @@ public class XingHanCommandTypeConstants {
* 星汉设备发送消息 (XingHan send msg)
*/
public static final String XingHan_ESEND_MSG = "Light_103";
/**
* 星汉设备发送紧急通知 (XingHan break news)
*/
public static final String XingHan_BREAK_NEWS = "Light_104";
}

View File

@ -0,0 +1,143 @@
package com.fuyuanshen.global.mqtt.rule.xinghan;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import com.fuyuanshen.global.mqtt.constants.XingHanCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_BOOT_LOGO_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 星汉设备开机 LOGO 下发规则:
* <p>
* 1. 设备上行 sta_PicTarns=great! => 仅标记成功<br>
* 2. 设备上行 sta_PicTarns=数字 => 下发第 N 块数据256B/块,带 CRC32
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class XinghanBootLogoRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
private final ObjectMapper objectMapper;
@Override
public String getCommandType() {
return XingHanCommandTypeConstants.XingHan_BOOT_LOGO;
}
@Override
public void execute(MqttRuleContext ctx) {
final String functionAccessKey = FUNCTION_ACCESS_KEY + ctx.getDeviceImei();
try {
MqttXinghanLogoJson payload = objectMapper.convertValue(
ctx.getPayloadDict(), MqttXinghanLogoJson.class);
String respText = payload.getStaPicTrans();
log.warn("设备上报LOGO{}", respText);
// 1. great! —— 成功标记
if ("great!".equalsIgnoreCase(respText)) {
RedisUtils.setCacheObject(functionAccessKey,
FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
log.info("设备 {} 开机 LOGO 写入成功", ctx.getDeviceImei());
return;
}
// 2. 数字 —— 下发数据块
int blockIndex;
try {
blockIndex = Integer.parseInt(respText);
} catch (NumberFormatException ex) {
log.warn("设备 {} LOGO 上报非法块号:{}", ctx.getDeviceImei(), respText);
return;
}
String hexImage = RedisUtils.getCacheObject(
GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + ctx.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX);
if (StringUtils.isEmpty(hexImage)) {
return;
}
byte[] fullBin = ImageToCArrayConverter.convertStringToByteArray(hexImage);
byte[] chunk = ImageToCArrayConverter.getChunk(fullBin, blockIndex - 1, CHUNK_SIZE);
log.info("设备 {} 第 {} 块数据长度: {} bytes", ctx.getDeviceImei(), blockIndex, chunk.length);
// 组装下发数据
ArrayList<Integer> dataFrame = new ArrayList<>();
dataFrame.add(blockIndex); // 块号
ImageToCArrayConverter.buildArr(convertHexToDecimal(chunk), dataFrame);
dataFrame.addAll(crc32AsList(chunk)); // CRC32
Map<String, Object> pub = new HashMap<>();
pub.put("ins_PicTrans", dataFrame);
String topic = MqttConstants.GLOBAL_PUB_KEY + ctx.getDeviceImei();
String json = JsonUtils.toJsonString(pub);
mqttGateway.sendMsgToMqtt(topic, 1, json);
log.info("下发开机 LOGO 数据 => topic:{}, payload:{}", topic, json);
} catch (Exception e) {
log.error("处理设备 {} 开机 LOGO 失败", ctx.getDeviceImei(), e);
RedisUtils.setCacheObject(functionAccessKey,
FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
/* ---------- 内部工具 ---------- */
private static final int CHUNK_SIZE = 256;
private static ArrayList<Integer> crc32AsList(byte[] data) {
CRC32 crc = new CRC32();
crc.update(data);
byte[] crcBytes = ByteBuffer.allocate(4)
.order(ByteOrder.BIG_ENDIAN)
.putInt((int) crc.getValue())
.array();
ArrayList<Integer> list = new ArrayList<>(4);
for (byte b : crcBytes) {
list.add(Byte.toUnsignedInt(b));
}
return list;
}
/* ---------- DTO ---------- */
@Data
private static class MqttXinghanLogoJson {
/**
* 设备上行:
* 数字 -> 请求对应块号
* great! -> 写入成功
*/
@JsonProperty("sta_PicTrans")
private String staPicTrans;
}
}

View File

@ -0,0 +1,117 @@
package com.fuyuanshen.global.mqtt.rule.xinghan;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
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.MqttConstants;
import com.fuyuanshen.global.mqtt.constants.XingHanCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
/**
* 星汉设备发送消息 下发规则:
* <p>
* 1. 设备上行 sta_TexTarns=genius! => 仅标记成功<br>
* 2. 设备上行 sta_TexTarns=数字 => GBK编码每行文字为一包一共4包第一字节为包序号
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class XinghanSendMsgRule implements MqttMessageRule {
private final MqttGateway mqttGateway;
private final ObjectMapper objectMapper;
@Override
public String getCommandType() {
return XingHanCommandTypeConstants.XingHan_ESEND_MSG;
}
@Override
public void execute(MqttRuleContext ctx) {
String functionAccess = FUNCTION_ACCESS_KEY + ctx.getDeviceImei();
try {
XinghanSendMsgRule.MqttXinghanMsgJson payload = objectMapper.convertValue(
ctx.getPayloadDict(), XinghanSendMsgRule.MqttXinghanMsgJson.class);
String respText = payload.getStaTexTrans();
log.info("设备上报人员信息: {} ", respText);
// 1. genius! —— 成功标记
if ("genius!".equalsIgnoreCase(respText)) {
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
log.info("设备 {} 发送消息完成", ctx.getDeviceImei());
return;
}
// 2. 数字 —— 下发数据块
int blockIndex;
try {
blockIndex = Integer.parseInt(respText);
} catch (NumberFormatException ex) {
log.warn("设备 {} 消息上报非法块号:{}", ctx.getDeviceImei(), respText);
return;
}
// 将发送的信息原文本以List<String>形式存储在Redis中
List<String> data = RedisUtils.getCacheList(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + ctx.getDeviceImei() + ":app_send_message_data");
if (data.isEmpty()) {
return;
}
//
ArrayList<Integer> intData = new ArrayList<>();
intData.add(blockIndex);
// 获取块原内容 转成GBK 再转成无符号十进制整数
String blockTxt = data.get(blockIndex-1);
// 再按 GBK 编码把字符串转成字节数组,并逐个转为无符号十进制整数
for (byte b : blockTxt.getBytes(GBK)) {
intData.add(b & 0xFF); // b & 0xFF 得到 0~255 的整数
}
Map<String, Object> map = new HashMap<>();
map.put("ins_TexTrans", intData);
String topic = MqttConstants.GLOBAL_PUB_KEY + ctx.getDeviceImei();
String json = JsonUtils.toJsonString(map);
mqttGateway.sendMsgToMqtt(topic, 1, json);
log.info("发送设备信息数据到设备消息=>topic:{},payload:{}",
MqttConstants.GLOBAL_PUB_KEY + ctx.getDeviceImei(),
JsonUtils.toJsonString(map));
} catch (Exception e) {
log.error("处理发送设备信息时出错", e);
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
}
}
private static final Charset GBK = Charset.forName("GBK");
/* ---------- DTO ---------- */
@Data
private static class MqttXinghanMsgJson {
/**
* 设备上行:
* 数字 -> 请求对应块号
* genius! -> 写入成功
*/
@JsonProperty("sta_TexTrans")
private String staTexTrans;
}
}

View File

@ -18,7 +18,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* BJQ6170设备控制类
* web后台:设备控制类
*/
@Validated
@RequiredArgsConstructor

View File

@ -1,9 +1,22 @@
package com.fuyuanshen.web.controller.device;
import com.fuyuanshen.app.domain.dto.APPReNameDTO;
import com.fuyuanshen.app.domain.dto.AppRealTimeStatusDto;
import com.fuyuanshen.app.domain.vo.APPDeviceTypeVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import com.fuyuanshen.web.service.device.DeviceBizService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@ -12,199 +25,74 @@ import java.util.List;
import java.util.Map;
/**
* @author: 默苍璃
* @date: 2025-08-0810:40
* web后台:设备控制中心
*/
@Slf4j
@Tag(name = "web后台:设备控制中心", description = "web后台:设备控制中心")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/device/controlCenter")
public class DeviceControlCenterController {
public class DeviceControlCenterController extends BaseController {
private final DeviceBizService appDeviceService;
/**
* 获取设备基本信息
* @param deviceId 设备ID
* @return 设备基本信息
* 查询设备列表
*/
@GetMapping("/info/{deviceId}")
public ResponseEntity<Map<String, Object>> getDeviceInfo(@PathVariable String deviceId) {
// 实际应用中这里会从数据库查询设备信息
Map<String, Object> deviceInfo = new HashMap<>();
deviceInfo.put("deviceName", "6170零零一");
deviceInfo.put("deviceModel", "BJQ6170");
deviceInfo.put("deviceId", deviceId);
deviceInfo.put("status", "在线");
deviceInfo.put("batteryLevel", 85);
return ResponseEntity.ok(deviceInfo);
@GetMapping("/list")
public TableDataInfo<WebDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return appDeviceService.queryWebDeviceList(bo, pageQuery);
}
/**
* 设置灯光模式
* @param lightModeRequest 灯光模式请求
* @return 操作结果
* 绑定设备
*/
@PostMapping("/light-mode")
public ResponseEntity<Map<String, Object>> setLightMode(@RequestBody LightModeRequest lightModeRequest) {
// 实际应用中这里会控制设备灯光
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
// response.put("message", "灯光模式已设置为: " + lightModeRequest.getMode());
// response.put("deviceId", lightModeRequest.getDeviceId());
// response.put("mode", lightModeRequest.getMode());
@PostMapping("/bind")
public R<Void> bind(@RequestBody AppDeviceBo bo) {
return toAjax(appDeviceService.bindDevice(bo));
}
return ResponseEntity.ok(response);
/**
* 解绑设备
*/
@DeleteMapping("/unBind")
public R<Void> unBind(Long id) {
return toAjax(appDeviceService.unBindDevice(id));
}
/**
* 更新人员信息
* @param personInfo 人员信息
* @return 操作结果
* 查询设备类型列表
*/
@PostMapping("/person-info")
public ResponseEntity<Map<String, Object>> updatePersonInfo(@RequestBody PersonInfo personInfo) {
// 实际应用中这里会更新数据库
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "人员信息已更新");
// response.put("unit", personInfo.getUnit());
// response.put("position", personInfo.getPosition());
return ResponseEntity.ok(response);
@GetMapping(value = "/typeList")
public R<List<APPDeviceTypeVo>> getTypeList() {
List<APPDeviceTypeVo> typeList = appDeviceService.getTypeList();
return R.ok(typeList);
}
/**
* 管理开机画面内容
* @param bootScreenRequest 开机画面请求
* @return 操作结果
* 重命名设备
*
* @param reNameDTO
* @return
*/
@PostMapping("/boot-screen")
public ResponseEntity<Map<String, Object>> manageBootScreen(@RequestBody BootScreenRequest bootScreenRequest) {
// 实际应用中这里会更新设备开机画面
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "开机画面内容已更新");
// response.put("deviceId", bootScreenRequest.getDeviceId());
// response.put("screens", bootScreenRequest.getScreens());
@PostMapping(value = "/reName")
public R<String> reName(@Validated @RequestBody APPReNameDTO reNameDTO) {
appDeviceService.reName(reNameDTO);
return R.ok("重命名成功!!!");
}
return ResponseEntity.ok(response);
@GetMapping("/realTimeStatus")
public R<Map<String, Object>> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
Map<String, Object> status = appDeviceService.getRealTimeStatus(statusDto);
return R.ok(status);
}
/**
* 设置灯光亮度
* @param brightnessRequest 亮度请求
* @return 操作结果
* 根据mac查询设备信息
*/
@PostMapping("/brightness")
public ResponseEntity<Map<String, Object>> setBrightness(@RequestBody BrightnessRequest brightnessRequest) {
// 实际应用中这里会控制设备亮度
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
// response.put("message", "灯光亮度已设置为: " + brightnessRequest.getBrightness() + "%");
// response.put("deviceId", brightnessRequest.getDeviceId());
// response.put("brightness", brightnessRequest.getBrightness());
// response.put("forceAlarm", brightnessRequest.isForceAlarm());
return ResponseEntity.ok(response);
}
/**
* 获取设备位置信息
* @param deviceId 设备ID
* @return 位置信息
*/
@GetMapping("/location/{deviceId}")
public ResponseEntity<Map<String, Object>> getLocation(@PathVariable String deviceId) {
// 实际应用中这里会从设备获取实时位置
Map<String, Object> locationInfo = new HashMap<>();
locationInfo.put("deviceId", deviceId);
locationInfo.put("longitude", "114°7'E");
locationInfo.put("latitude", "30'28'N");
locationInfo.put("address", "湖北省武汉市洪山区光谷大道国际企业中心");
locationInfo.put("timestamp", new Date());
return ResponseEntity.ok(locationInfo);
}
/**
* 发送紧急消息
* @param messageRequest 消息请求
* @return 操作结果
*/
@PostMapping("/send-message")
public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody MessageRequest messageRequest) {
// 实际应用中这里会向设备发送消息
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "消息已发送");
// response.put("deviceId", messageRequest.getDeviceId());
// response.put("content", messageRequest.getContent());
response.put("timestamp", new Date());
return ResponseEntity.ok(response);
}
/**
* 管理操作视频
* @param videoRequest 视频请求
* @return 操作结果
*/
@PostMapping("/operation-video")
public ResponseEntity<Map<String, Object>> manageOperationVideo(@RequestBody VideoRequest videoRequest) {
// 实际应用中这里会更新设备操作视频
Map<String, Object> response = new HashMap<>();
response.put("code", 200);
response.put("message", "操作视频已更新");
// response.put("deviceId", videoRequest.getDeviceId());
// response.put("videoUrl", videoRequest.getVideoUrl());
return ResponseEntity.ok(response);
}
// 请求对象类定义
public static class LightModeRequest {
private String deviceId;
private String mode; // 强光、弱光、爆闪、泛光、激光
// Getters and Setters
}
public static class PersonInfo {
private String deviceId;
private String unit; // 单位
private String position; // 职位
// Getters and Setters
}
public static class BootScreenRequest {
private String deviceId;
private List<String> screens; // 产品参数、操作说明等
// Getters and Setters
}
public static class BrightnessRequest {
private String deviceId;
private int brightness; // 0-100
private boolean forceAlarm; // 强制报警
// Getters and Setters
}
public static class MessageRequest {
private String deviceId;
private String content; // 消息内容
// Getters and Setters
}
public static class VideoRequest {
private String deviceId;
private String videoUrl; // 视频链接
// Getters and Setters
@GetMapping("/getDeviceInfoByDeviceMac")
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
}
}

View File

@ -8,9 +8,11 @@ import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import com.fuyuanshen.web.service.WEBDeviceService;
import com.fuyuanshen.web.service.device.DeviceBizService;
import io.swagger.v3.oas.annotations.Operation;
@ -36,7 +38,6 @@ import java.util.Map;
public class WEBDeviceController extends BaseController {
private final WEBDeviceService deviceService;
private final DeviceBizService appDeviceService;
/**
@ -54,65 +55,19 @@ public class WEBDeviceController extends BaseController {
/**
* 查询设备列表
*/
@GetMapping("/list")
public TableDataInfo<AppDeviceVo> list(DeviceQueryCriteria bo, PageQuery pageQuery) {
return appDeviceService.queryAppDeviceList(bo, pageQuery);
}
/**
* 绑定设备
*/
@PostMapping("/bind")
public R<Void> bind(@RequestBody AppDeviceBo bo) {
return toAjax(appDeviceService.bindDevice(bo));
}
/**
* 解绑设备
*/
@DeleteMapping("/unBind")
public R<Void> unBind(Long id) {
return toAjax(appDeviceService.unBindDevice(id));
}
/**
* 查询设备类型列表
*/
@GetMapping(value = "/typeList")
public R<List<APPDeviceTypeVo>> getTypeList() {
List<APPDeviceTypeVo> typeList = appDeviceService.getTypeList();
return R.ok(typeList);
}
/**
* 重命名设备
* 设备详情
*
* @param reNameDTO
* @param id
* @return
*/
@PostMapping(value = "/reName")
public R<String> reName(@Validated @RequestBody APPReNameDTO reNameDTO) {
appDeviceService.reName(reNameDTO);
return R.ok("重命名成功!!!");
@Operation(summary = "设备详情")
@GetMapping(value = "/pc/detail/{id}")
public R<WebDeviceVo> getDevice(@PathVariable Long id) {
WebDeviceVo device = deviceService.getDevice(id);
return R.ok(device);
}
@GetMapping("/realTimeStatus")
public R<Map<String, Object>> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
Map<String, Object> status = appDeviceService.getRealTimeStatus(statusDto);
return R.ok(status);
}
/**
* 根据mac查询设备信息
*/
@GetMapping("/getDeviceInfoByDeviceMac")
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
}
}

View File

@ -10,6 +10,7 @@ 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 com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import java.io.IOException;
import java.util.List;
@ -29,4 +30,12 @@ public interface WEBDeviceService extends IService<Device> {
*/
int webUnBindDevice(Long id, Long userId);
/**
* WEB端设备详情
*
* @param id
* @return
*/
WebDeviceVo getDevice(Long id);
}

View File

@ -1,16 +1,19 @@
package com.fuyuanshen.web.service.device;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.AppPersonnelInfoRecords;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.app.mapper.AppPersonnelInfoRecordsMapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.*;
@ -50,6 +53,7 @@ public class DeviceBJQBizService {
private final DeviceMapper deviceMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
private final AppPersonnelInfoRecordsMapper appPersonnelInfoRecordsMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final MqttGateway mqttGateway;
private final DeviceLogMapper deviceLogMapper;
@ -242,11 +246,18 @@ public class DeviceBJQBizService {
map.put("instruct", intData);
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), 1, JSON.toJSONString(map));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), bo);
recordDeviceLog(deviceId, deviceObj.getDeviceName(), "人员信息登记", JSON.toJSONString(bo), AppLoginHelper.getUserId());
String logContent = "单位:"+bo.getUnitName()+",职位:"+bo.getPosition()+",姓名:"+bo.getName()+",ID"+bo.getCode();
recordDeviceLog(deviceId, deviceObj.getDeviceName(), "人员信息登记", logContent, AppLoginHelper.getUserId());
if (ObjectUtils.length(appPersonnelInfoVos) == 0) {
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
return appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
AppPersonnelInfoRecords appPersonnelInfoRecords = new AppPersonnelInfoRecords();
BeanUtil.copyProperties(appPersonnelInfo, appPersonnelInfoRecords);
appPersonnelInfoRecords.setId(null);
appPersonnelInfoRecords.setPersonnelId(appPersonnelInfo.getId());
appPersonnelInfoRecordsMapper.insert(appPersonnelInfoRecords);
} else {
UpdateWrapper<AppPersonnelInfo> uw = new UpdateWrapper<>();
uw.eq("device_id", deviceId)
@ -254,10 +265,52 @@ public class DeviceBJQBizService {
.set("position", bo.getPosition())
.set("unit_name", bo.getUnitName())
.set("code", bo.getCode());
return appPersonnelInfoMapper.update(null, uw) > 0;
appPersonnelInfoMapper.update(null, uw);
AppPersonnelInfoVo personnelInfoVo = appPersonnelInfoVos.get(0);
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
AppPersonnelInfoRecords appPersonnelInfoRecords = new AppPersonnelInfoRecords();
BeanUtil.copyProperties(appPersonnelInfo, appPersonnelInfoRecords);
appPersonnelInfoRecords.setId(null);
appPersonnelInfoRecords.setPersonnelId(personnelInfoVo.getId());
appPersonnelInfoRecordsMapper.insert(appPersonnelInfoRecords);
}
return true;
}
public void uploadDeviceLogo2(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);
log.info("长度:" + largeData.length);
// 在获取 largeData 后,将其与前缀合并
byte[] prefix = new byte[]{0x50, 0x49, 0x43, 0x54, 0x55, 0x52, 0x45}; // "PICTURE"
byte[] combinedData = new byte[prefix.length + largeData.length];
System.arraycopy(prefix, 0, combinedData, 0, prefix.length);
System.arraycopy(largeData, 0, combinedData, prefix.length, largeData.length);
// 将 combinedData 转换为十六进制表示
String[] hexArray = new String[combinedData.length];
for (int i = 0; i < combinedData.length; i++) {
hexArray[i] = String.format("0x%02X", combinedData[i]);
}
// Map<String, Object> map = new HashMap<>();
// map.put("instruct", combinedData);
String[] specificChunk = ImageToCArrayConverter.getChunk2(hexArray, 0, bo.getChunkSize());
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(), 1 , Arrays.toString(specificChunk));
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),Arrays.toString(specificChunk));
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", "上传开机画面", AppLoginHelper.getUserId());
} catch (Exception e){
e.printStackTrace();
throw new ServiceException("发送指令失败");
}
}
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
try {
Device device = deviceMapper.selectById(bo.getDeviceId());

View File

@ -28,6 +28,7 @@ import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
import com.fuyuanshen.equipment.domain.vo.AppDeviceVo;
import com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
@ -123,6 +124,47 @@ public class DeviceBizService {
return TableDataInfo.build(result);
}
public TableDataInfo<WebDeviceVo> queryWebDeviceList(DeviceQueryCriteria bo, PageQuery pageQuery) {
Page<WebDeviceVo> result = deviceMapper.queryWebDeviceList(pageQuery.build(), bo);
List<WebDeviceVo> records = result.getRecords();
if(records != null && !records.isEmpty()){
records.forEach(item -> {
if(item.getCommunicationMode()!=null && item.getCommunicationMode() == 0){
//设备在线状态
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
if(StringUtils.isNotBlank(onlineStatus)){
item.setOnlineStatus(1);
}else{
item.setOnlineStatus(0);
}
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX+ item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
// 获取电量
if(StringUtils.isNotBlank(deviceStatus)){
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
item.setBattery(jsonObject.getString("batteryPercentage"));
}else{
item.setBattery("0");
}
String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ item.getDeviceImei()+ DEVICE_LOCATION_KEY_PREFIX);
if(StringUtils.isNotBlank(location)){
JSONObject jsonObject = JSONObject.parseObject(location);
item.setLatitude(jsonObject.getString("latitude"));
item.setLongitude(jsonObject.getString("longitude"));
}
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ item.getDeviceImei()+ DEVICE_ALARM_KEY_PREFIX);
if(StringUtils.isNotBlank(alarmStatus)){
item.setAlarmStatus(alarmStatus);
}
}
});
}
return TableDataInfo.build(result);
}
public int bindDevice(AppDeviceBo bo) {
Integer mode = bo.getCommunicationMode();
Long userId = AppLoginHelper.getUserId();

View File

@ -0,0 +1,269 @@
package com.fuyuanshen.web.service.device;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppPersonnelInfo;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppPersonnelInfoVo;
import com.fuyuanshen.app.mapper.AppPersonnelInfoMapper;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.exception.ServiceException;
import com.fuyuanshen.common.core.utils.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.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.equipment.enums.LightModeEnum;
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.Duration;
import java.util.*;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.buildArr;
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.generateFixedBitmapData;
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_BOOT_LOGO_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceXinghanBizService {
private final DeviceMapper deviceMapper;
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
private final DeviceTypeMapper deviceTypeMapper;
private final MqttGateway mqttGateway;
private final DeviceLogMapper deviceLogMapper;
/**
* 所有档位的描述表
* key : 指令类型,如 "ins_DetectGrade"、"ins_LightGrade" ……
* value : Map<Integer,String> 值 -> 描述
*/
private static final Map<String, Map<Integer, String>> GRADE_DESC = Map.of(
"ins_DetectGrade", Map.of(1, "低档", 2, "中档", 3, "高档"),
"ins_LightGrade", Map.of(1, "强光", 2, "弱光"),
"ins_SOSGrade", Map.of(1, "爆闪模式", 2, "红蓝模式"),
"ins_ShakeBit", Map.of(0, "未静止报警", 1, "正在静止报警")
// 再加 4、5、6…… 档,直接往 Map 里塞即可
);
/**
* 根据指令类型和值,返回中文描述
*/
private static String resolveGradeDesc(String type, int value) {
return GRADE_DESC.getOrDefault(type, Map.of())
.getOrDefault(value, "关闭");
}
/**
* 设置静电预警档位
*/
public void upDetectGradeSettings(DeviceInstructDto dto) {
sendCommand(dto, "ins_DetectGrade","静电预警档位");
}
/**
* 设置照明档位
*/
public void upLightGradeSettings(DeviceInstructDto dto) {
sendCommand(dto, "ins_LightGrade","照明档位");
}
/**
* 设置SOS档位
*/
public void upSOSGradeSettings(DeviceInstructDto dto) {
sendCommand(dto, "ins_SOSGrade","SOS档位");
}
/**
* 设置强制报警
*/
public void upShakeBitSettings(DeviceInstructDto dto) {
sendCommand(dto, "ins_ShakeBit","强制报警");
}
/**
* 上传设备logo
*/
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
try {
Device device = deviceMapper.selectById(bo.getDeviceId());
if (device == null) {
throw new ServiceException("设备不存在");
}
if (isDeviceOffline(device.getDeviceImei())) {
throw new ServiceException("设备已断开连接:" + device.getDeviceName());
}
MultipartFile file = bo.getFile();
byte[] largeData = ImageToCArrayConverter.convertImageToCArray(file.getInputStream(), 160, 80, 25600);
log.info("长度:" + largeData.length);
log.info("原始数据大小: {} 字节", largeData.length);
int[] ints = convertHexToDecimal(largeData);
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() +DEVICE_BOOT_LOGO_KEY_PREFIX, Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
Map<String, Object> payload = Map.of("ins_PicTrans",
Collections.singletonList(0));
String topic = MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei();
String json = JsonUtils.toJsonString(payload);
try {
mqttGateway.sendMsgToMqtt(topic, 1, json);
} catch (Exception e) {
log.error("上传开机画面失败, topic={}, payload={}", topic, json, e);
throw new ServiceException("上传LOGO失败" + e.getMessage());
}
log.info("发送上传开机画面到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY+device.getDeviceImei(),json);
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", "上传开机画面", AppLoginHelper.getUserId());
} catch (Exception e){
throw new ServiceException("发送指令失败");
}
}
/**
* 人员登记
* @param bo
*/
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
Long deviceId = bo.getDeviceId();
Device deviceObj = deviceMapper.selectById(deviceId);
if (deviceObj == null) {
throw new RuntimeException("请先将设备入库!!!");
}
if (isDeviceOffline(deviceObj.getDeviceImei())) {
throw new ServiceException("设备已断开连接:" + deviceObj.getDeviceName());
}
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
.eq("device_id", deviceId);
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
List<String> list = new ArrayList<>();
list.add(bo.getUnitName());
list.add(bo.getName());
list.add(bo.getPosition());
list.add(bo.getCode());
RedisUtils.setCacheList(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + deviceObj.getDeviceImei() + ":app_send_message_data", list);
Map<String, Object> payload = Map.of("ins_TexTrans",
Collections.singletonList(0));
String topic = MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei();
String json = JsonUtils.toJsonString(payload);
try {
mqttGateway.sendMsgToMqtt(topic, 1, json);
} catch (Exception e) {
log.error("人员信息登记失败, topic={}, payload={}", topic, json, e);
throw new ServiceException("人员信息登记失败:" + e.getMessage());
}
log.info("发送人员信息登记到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), bo);
recordDeviceLog(deviceId, deviceObj.getDeviceName(), "人员信息登记", JSON.toJSONString(bo), AppLoginHelper.getUserId());
if (ObjectUtils.length(appPersonnelInfoVos) == 0) {
AppPersonnelInfo appPersonnelInfo = MapstructUtils.convert(bo, AppPersonnelInfo.class);
return appPersonnelInfoMapper.insertOrUpdate(appPersonnelInfo);
} else {
UpdateWrapper<AppPersonnelInfo> uw = new UpdateWrapper<>();
uw.eq("device_id", deviceId)
.set("name", bo.getName())
.set("position", bo.getPosition())
.set("unit_name", bo.getUnitName())
.set("code", bo.getCode());
return appPersonnelInfoMapper.update(null, uw) > 0;
}
}
/* ---------------------------------- 私有通用方法 ---------------------------------- */
private void sendCommand(DeviceInstructDto dto,
String payloadKey,String deviceAction) {
long deviceId = dto.getDeviceId();
Device device = deviceMapper.selectById(deviceId);
if (device == null) {
throw new ServiceException("设备不存在");
}
if (isDeviceOffline(device.getDeviceImei())) {
throw new ServiceException("设备已断开连接:" + device.getDeviceName());
}
Integer value = Integer.parseInt(dto.getInstructValue());
Map<String, Object> payload = Map.of(payloadKey,
Collections.singletonList(value));
String topic = MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei();
String json = JsonUtils.toJsonString(payload);
try {
mqttGateway.sendMsgToMqtt(topic, 1, json);
} catch (Exception e) {
log.error("发送指令失败, topic={}, payload={}", topic, json, e);
throw new ServiceException("发送指令失败:" + e.getMessage());
}
log.info("发送指令成功 => topic:{}, payload:{}", topic, json);
String content = resolveGradeDesc("ins_DetectGrade", value);
recordDeviceLog(device.getId(),
device.getDeviceName(),
deviceAction,
content,
AppLoginHelper.getUserId());
}
private boolean isDeviceOffline(String imei) {
// 原方法名语义相反,这里取反,使含义更清晰
return getDeviceStatus(imei);
}
/**
* 记录设备操作日志
* @param deviceId 设备ID
* @param content 日志内容
* @param operator 操作人
*/
private void recordDeviceLog(Long deviceId,String deviceName, String deviceAction, String content, Long operator) {
try {
// 创建设备日志实体
com.fuyuanshen.equipment.domain.DeviceLog deviceLog = new com.fuyuanshen.equipment.domain.DeviceLog();
deviceLog.setDeviceId(deviceId);
deviceLog.setDeviceAction(deviceAction);
deviceLog.setContent(content);
deviceLog.setCreateBy(operator);
deviceLog.setDeviceName(deviceName);
deviceLog.setCreateTime(new Date());
// 插入日志记录
deviceLogMapper.insert(deviceLog);
} catch (Exception e) {
log.error("记录设备操作日志失败: {}", e.getMessage(), e);
}
}
private boolean getDeviceStatus(String deviceImei) {
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
return StringUtils.isBlank(deviceOnlineStatusRedisKey);
}
}

View File

@ -1,12 +1,17 @@
package com.fuyuanshen.web.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.app.domain.AppDeviceBindRecord;
import com.fuyuanshen.app.domain.AppDeviceShare;
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
import com.fuyuanshen.app.mapper.AppDeviceBindRecordMapper;
import com.fuyuanshen.app.mapper.AppDeviceShareMapper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceAssignments;
import com.fuyuanshen.equipment.domain.vo.WebDeviceVo;
import com.fuyuanshen.equipment.enums.BindingStatusEnum;
import com.fuyuanshen.equipment.mapper.DeviceAssignmentsMapper;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
@ -27,13 +32,12 @@ import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
public class WEBDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements WEBDeviceService {
private final DeviceBizService appDeviceService;
private final DeviceAssignmentsMapper deviceAssignmentsMapper;
private final AppDeviceBindRecordMapper appDeviceBindRecordMapper;
private final DeviceMapper deviceMapper;
private final AppDeviceShareMapper appDeviceShareMapper;
/**
@ -70,4 +74,25 @@ public class WEBDeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impl
}
/**
* WEB端设备详情
*
* @param id
* @return
*/
@Override
public WebDeviceVo getDevice(Long id) {
Device device = deviceMapper.selectById(id);
if (device != null) {
WebDeviceVo webDeviceVo = new WebDeviceVo();
BeanUtil.copyProperties(device, webDeviceVo);
// 查询分享用户数
Long count = appDeviceShareMapper.selectCount(new QueryWrapper<AppDeviceShare>().eq("device_id", id));
webDeviceVo.setShareUsersNumber(Math.toIntExact(count));
return webDeviceVo;
}
return null;
}
}