Compare commits
40 Commits
07e60cf7f0
...
dyf-device
| Author | SHA1 | Date | |
|---|---|---|---|
| 7753444f25 | |||
| bf182ebc89 | |||
| d5a29feca3 | |||
| 0457877c09 | |||
| 1e9e815314 | |||
| b18ab98feb | |||
| 7c6f3be844 | |||
| aa69b552aa | |||
| 3dd0d4cc90 | |||
| 00a4394b43 | |||
| 2376a3b42a | |||
| 359cabbd2c | |||
| 76c11fff15 | |||
| a0ab5e9fe0 | |||
| 891ee7c1c9 | |||
| a145c372b8 | |||
| 3798e52ee0 | |||
| 6488b8a724 | |||
| 6d58268874 | |||
| 88b54a49f4 | |||
| 56dbfbde71 | |||
| dce043f63d | |||
| 77626673e9 | |||
| 759c72fc65 | |||
| 1be80be309 | |||
| 92df1c8668 | |||
| cc2b7664a8 | |||
| 33d6108172 | |||
| 70c416779f | |||
| ee85961eeb | |||
| 004079f7f4 | |||
| 264d0135d9 | |||
| 4961ec47f8 | |||
| f25afe0e9d | |||
| e265dea0ec | |||
| c7ff118bfe | |||
| 1dc3386284 | |||
| c4957aa3aa | |||
| f4369f7581 | |||
| df28eed305 |
@ -1,24 +1,24 @@
|
||||
package com.fuyuanshen;
|
||||
package com.fuyuanshen;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 启动程序
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class DromaraApplication {
|
||||
/**
|
||||
* 启动程序
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class DromaraApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(DromaraApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ fys-Vue-Plus启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(DromaraApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ fys-Vue-Plus启动成功 ლ(´ڡ`ლ)゙");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -72,10 +72,8 @@ public class AppAuthController {
|
||||
|
||||
private final AppLoginService loginService;
|
||||
private final AppRegisterService registerService;
|
||||
private final ISysConfigService configService;
|
||||
private final ISysTenantService tenantService;
|
||||
private final ISysClientService clientService;
|
||||
private final ISysDictTypeService dictTypeService;
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@ -92,4 +92,5 @@ public class AppDeviceController extends BaseController {
|
||||
public R<AppDeviceVo> getDeviceInfo(String deviceMac) {
|
||||
return R.ok(appDeviceService.getDeviceInfo(deviceMac));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -44,10 +44,9 @@ import static com.fuyuanshen.common.core.constant.GlobalConstants.DEVICE_SHARE_C
|
||||
@RequestMapping("/app/deviceShare")
|
||||
public class AppDeviceShareController extends BaseController {
|
||||
|
||||
private final IAppDeviceShareService deviceShareService;
|
||||
|
||||
private final AppDeviceShareService appDeviceShareService;
|
||||
|
||||
|
||||
/**
|
||||
* 分享管理列表
|
||||
*/
|
||||
@ -95,6 +94,7 @@ public class AppDeviceShareController extends BaseController {
|
||||
return toAjax(appDeviceShareService.remove(ids));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 短信验证码
|
||||
*
|
||||
@ -116,4 +116,5 @@ public class AppDeviceShareController extends BaseController {
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -25,6 +25,7 @@ public class AppFileController extends BaseController {
|
||||
|
||||
private final AppFileService appFileService;
|
||||
|
||||
|
||||
/**
|
||||
* 查询文件列表
|
||||
*/
|
||||
@ -33,6 +34,7 @@ public class AppFileController extends BaseController {
|
||||
return R.ok(appFileService.list(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*/
|
||||
@ -52,4 +54,5 @@ public class AppFileController extends BaseController {
|
||||
}
|
||||
return toAjax(appFileService.delete(ids));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -25,6 +25,7 @@ public class AppOperationVideoController extends BaseController {
|
||||
|
||||
private final IAppOperationVideoService appOperationVideoService;
|
||||
|
||||
|
||||
/**
|
||||
* 查询操作视频列表
|
||||
*/
|
||||
@ -68,4 +69,5 @@ public class AppOperationVideoController extends BaseController {
|
||||
public R<Void> deleteOperationVideo(@PathVariable Long id) {
|
||||
return toAjax(appOperationVideoService.deleteWithValidByIds(List.of(id), true));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
package com.fuyuanshen.app.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaIgnore;
|
||||
import com.fuyuanshen.app.service.AudioProcessService;
|
||||
import com.fuyuanshen.app.service.VideoProcessService;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
@ -28,10 +29,13 @@ public class AppVideoController extends BaseController {
|
||||
private final VideoProcessService videoProcessService;
|
||||
private final AudioProcessService audioProcessService;
|
||||
|
||||
/**
|
||||
* 上传视频转码code默认1:RGB565 2:BGR565
|
||||
*/
|
||||
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
|
||||
public R<List<String>> uploadVideo(@RequestParam("file") MultipartFile file) {
|
||||
return R.ok(videoProcessService.processVideo(file));
|
||||
public R<List<String>> uploadVideo(@RequestParam("file") MultipartFile file, @RequestParam(defaultValue = "1") int code) {
|
||||
return R.ok(videoProcessService.processVideo(file, code));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -51,4 +55,13 @@ public class AppVideoController extends BaseController {
|
||||
public R<List<String>> uploadAudioTTS(@RequestParam String text) throws IOException {
|
||||
return R.ok(audioProcessService.generateStandardPcmData(text));
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取文本内容(只支持txt/docx)
|
||||
*/
|
||||
@PostMapping(value = "/extract", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@RepeatSubmit(interval = 2, timeUnit = TimeUnit.SECONDS,message = "请勿重复提交!")
|
||||
public R<String> extract(@RequestParam("file") MultipartFile file) throws Exception {
|
||||
return R.ok("Success",audioProcessService.extract(file));
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,6 +31,7 @@ public class AppDeviceBJQController extends BaseController {
|
||||
|
||||
private final DeviceBJQBizService appDeviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
@ -86,7 +87,6 @@ public class AppDeviceBJQController extends BaseController {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式
|
||||
* 0(关灯),1(强光模式),2(弱光模式), 3(爆闪模式), 4(泛光模式)
|
||||
|
||||
@ -28,6 +28,7 @@ public class AppDeviceHBYController extends BaseController {
|
||||
|
||||
private final DeviceBJQBizService appDeviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
|
||||
@ -38,6 +38,8 @@ public class AppDeviceXinghanController extends BaseController {
|
||||
|
||||
private final DeviceXinghanBizService appDeviceService;
|
||||
private final DeviceService deviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记
|
||||
*/
|
||||
@ -67,7 +69,7 @@ public class AppDeviceXinghanController extends BaseController {
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if(file.getSize()>1024*1024*2){
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService.uploadDeviceLogo(bo);
|
||||
@ -125,7 +127,7 @@ public class AppDeviceXinghanController extends BaseController {
|
||||
|
||||
@GetMapping(value = "/typeAll")
|
||||
@Operation(summary = "查询所有设备类型")
|
||||
public R<List<DeviceType>> queryDeviceTypes() {
|
||||
public R<List<DeviceType>> queryDeviceTypes() {
|
||||
List<DeviceType> deviceTypes = appDeviceService.queryDeviceTypes();
|
||||
return R.ok(deviceTypes);
|
||||
}
|
||||
|
||||
@ -28,6 +28,7 @@ public class TestController extends BaseController {
|
||||
|
||||
private final DeviceBJQBizService appDeviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 上传设备logo图片
|
||||
*/
|
||||
|
||||
@ -0,0 +1,156 @@
|
||||
package com.fuyuanshen.app.controller.device.bjq;
|
||||
|
||||
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
|
||||
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
|
||||
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
|
||||
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
import com.fuyuanshen.common.core.validate.AddGroup;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
|
||||
import com.fuyuanshen.common.web.core.BaseController;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
|
||||
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* BJQ6075 设备控制类
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/app/bjq6075/device")
|
||||
public class AppDeviceBJQ6075Controller extends BaseController {
|
||||
|
||||
private final DeviceBJQ6075BizService appDeviceService6075;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记 1
|
||||
*/
|
||||
@PostMapping(value = "/registerPersonInfo")
|
||||
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
|
||||
return toAjax(appDeviceService6075.registerPersonInfo(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送信息 2
|
||||
*/
|
||||
@PostMapping(value = "/sendMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
|
||||
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送报警信息 3
|
||||
*/
|
||||
@PostMapping(value = "/sendAlarmMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
|
||||
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传设备logo图片 4
|
||||
*/
|
||||
@PostMapping("/uploadLogo")
|
||||
@FunctionAccessAnnotation("uploadLogo")
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService6075.uploadDeviceLogo(bo);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 5
|
||||
* (主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
@PostMapping("/lightModeSettings")
|
||||
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 6
|
||||
* (辅光模式)
|
||||
* 0(关闭灯光),1(泛光),2(泛光爆闪), 3(警示灯), 4(警示灯/泛光)
|
||||
*/
|
||||
@PostMapping("/auxiliaryLightModeSettings")
|
||||
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光亮度设置 7
|
||||
*/
|
||||
@PostMapping("/lightBrightnessSettings")
|
||||
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightBrightnessSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 激光模式设置 8
|
||||
*/
|
||||
@PostMapping("/laserModeSettings")
|
||||
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 声光报警模式设置 9
|
||||
* Sound and light alarm
|
||||
*/
|
||||
@PostMapping("/salaModeSettings")
|
||||
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备分享详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/getShareInfo/{id}")
|
||||
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,155 @@
|
||||
package com.fuyuanshen.app.controller.device.bjq;
|
||||
|
||||
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
|
||||
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
|
||||
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
|
||||
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
import com.fuyuanshen.common.core.validate.AddGroup;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
|
||||
import com.fuyuanshen.common.web.core.BaseController;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
|
||||
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* BJQ6331便携式工作灯
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/app/BJQ6331/device")
|
||||
public class AppDeviceBJQ6331Controller extends BaseController {
|
||||
|
||||
private final DeviceBJQ6075BizService appDeviceService6075;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记 1
|
||||
*/
|
||||
@PostMapping(value = "/registerPersonInfo")
|
||||
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
|
||||
return toAjax(appDeviceService6075.registerPersonInfo(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送信息 2
|
||||
*/
|
||||
@PostMapping(value = "/sendMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
|
||||
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送报警信息 3
|
||||
*/
|
||||
@PostMapping(value = "/sendAlarmMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
|
||||
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传设备logo图片 4
|
||||
*/
|
||||
@PostMapping("/uploadLogo")
|
||||
@FunctionAccessAnnotation("uploadLogo")
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService6075.uploadDeviceLogo(bo);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 5
|
||||
* (主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
@PostMapping("/lightModeSettings")
|
||||
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 6
|
||||
* (辅光模式)
|
||||
* 0(关闭灯光),1(泛光),2(泛光爆闪), 3(警示灯), 4(警示灯/泛光)
|
||||
*/
|
||||
@PostMapping("/auxiliaryLightModeSettings")
|
||||
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光亮度设置 7
|
||||
*/
|
||||
@PostMapping("/lightBrightnessSettings")
|
||||
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightBrightnessSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 激光模式设置 8
|
||||
*/
|
||||
@PostMapping("/laserModeSettings")
|
||||
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 声光报警模式设置 9
|
||||
* Sound and light alarm
|
||||
*/
|
||||
@PostMapping("/salaModeSettings")
|
||||
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备分享详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/getShareInfo/{id}")
|
||||
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -0,0 +1,156 @@
|
||||
package com.fuyuanshen.app.controller.device.bjq;
|
||||
|
||||
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
|
||||
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
|
||||
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
|
||||
import com.fuyuanshen.app.domain.vo.AppDevice6075DetailVo;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
import com.fuyuanshen.common.core.validate.AddGroup;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
|
||||
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
|
||||
import com.fuyuanshen.common.web.core.BaseController;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
|
||||
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* HBY335(LED救生照明线)
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/app/HBY335/device")
|
||||
public class AppDeviceHBY335Controller extends BaseController {
|
||||
|
||||
private final DeviceBJQ6075BizService appDeviceService6075;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDevice6075DetailVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记 1
|
||||
*/
|
||||
@PostMapping(value = "/registerPersonInfo")
|
||||
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
|
||||
return toAjax(appDeviceService6075.registerPersonInfo(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送信息 2
|
||||
*/
|
||||
@PostMapping(value = "/sendMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
|
||||
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送报警信息 3
|
||||
*/
|
||||
@PostMapping(value = "/sendAlarmMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
|
||||
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService6075.sendAlarmMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传设备logo图片 4
|
||||
*/
|
||||
@PostMapping("/uploadLogo")
|
||||
@FunctionAccessAnnotation("uploadLogo")
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService6075.uploadDeviceLogo(bo);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 5
|
||||
* (主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
@PostMapping("/lightModeSettings")
|
||||
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式 6
|
||||
* (辅光模式)
|
||||
* 0(关闭灯光),1(泛光),2(泛光爆闪), 3(警示灯), 4(警示灯/泛光)
|
||||
*/
|
||||
@PostMapping("/auxiliaryLightModeSettings")
|
||||
public R<Void> auxiliaryLightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光亮度设置 7
|
||||
*/
|
||||
@PostMapping("/lightBrightnessSettings")
|
||||
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.lightBrightnessSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 激光模式设置 8
|
||||
*/
|
||||
@PostMapping("/laserModeSettings")
|
||||
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 声光报警模式设置 9
|
||||
* Sound and light alarm
|
||||
*/
|
||||
@PostMapping("/salaModeSettings")
|
||||
public R<Void> salaModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService6075.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备分享详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/getShareInfo/{id}")
|
||||
public R<AppDevice6075DetailVo> getShareInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService6075.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -11,8 +11,9 @@ public class AppDeviceLogoUploadDto {
|
||||
private Long deviceId;
|
||||
|
||||
private String deviceImei;
|
||||
|
||||
/**
|
||||
* 文件
|
||||
* 文件
|
||||
*/
|
||||
private MultipartFile file;
|
||||
|
||||
@ -25,4 +26,5 @@ public class AppDeviceLogoUploadDto {
|
||||
private List<Long> deviceIds;
|
||||
|
||||
private Integer chunkSize;
|
||||
|
||||
}
|
||||
|
||||
@ -8,9 +8,15 @@ public class DeviceInstructDto {
|
||||
private Long deviceId;
|
||||
|
||||
private String deviceImei;
|
||||
|
||||
/**
|
||||
* 下发指令
|
||||
* 下发指令
|
||||
*/
|
||||
private String instructValue;
|
||||
|
||||
/**
|
||||
* 下发指令类型
|
||||
*/
|
||||
private String instructType;
|
||||
|
||||
}
|
||||
|
||||
@ -216,6 +216,7 @@ public class AppDeviceShareService {
|
||||
uw.eq("phonenumber", bo.getPhonenumber());
|
||||
uw.set("permission", bo.getPermission());
|
||||
uw.set("update_by", userId);
|
||||
uw.set("create_by", userId);
|
||||
uw.set("update_time", new Date());
|
||||
|
||||
return appDeviceShareMapper.update(uw);
|
||||
|
||||
@ -4,6 +4,10 @@ import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceBindRecordBo;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceShareBo;
|
||||
import com.fuyuanshen.app.domain.vo.AppDeviceBindRecordVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppRoleVo;
|
||||
import com.fuyuanshen.app.domain.vo.AppUserVo;
|
||||
import com.fuyuanshen.common.core.constant.Constants;
|
||||
@ -33,6 +37,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 登录校验方法
|
||||
@ -52,6 +57,8 @@ public class AppLoginService {
|
||||
|
||||
private final ISysTenantService tenantService;
|
||||
private final IAppUserService appUserService;
|
||||
private final IAppDeviceShareService appDeviceShareService;
|
||||
private final IAppDeviceBindRecordService appDeviceBindRecordService;
|
||||
|
||||
|
||||
/**
|
||||
@ -188,10 +195,32 @@ public class AppLoginService {
|
||||
public void cancelAccount() {
|
||||
try {
|
||||
AppLoginUser loginUser = AppLoginHelper.getLoginUser();
|
||||
// AppLoginUser loginUser = new AppLoginUser();
|
||||
// loginUser.setUserId(1988398584423133187L);
|
||||
// loginUser.setUsername("19022528079");
|
||||
if (ObjectUtil.isNull(loginUser)) {
|
||||
return;
|
||||
}
|
||||
appUserService.deleteWithValidByIds(Collections.singletonList(loginUser.getUserId()),true);
|
||||
|
||||
AppDeviceBindRecordBo appDeviceBindRecordBo = new AppDeviceBindRecordBo();
|
||||
appDeviceBindRecordBo.setBindingUserId(loginUser.getUserId());
|
||||
List<AppDeviceBindRecordVo> appDeviceBindRecordVos = appDeviceBindRecordService.queryList(appDeviceBindRecordBo);
|
||||
if(ObjectUtil.length(appDeviceBindRecordVos)>0){
|
||||
|
||||
|
||||
// 根据设备id批量删除
|
||||
List<Long> deviceIds = appDeviceBindRecordVos.stream().map(AppDeviceBindRecordVo::getDeviceId).toList();
|
||||
appDeviceShareService.deleteByDeviceIds(deviceIds);
|
||||
|
||||
|
||||
List<Long> ids = appDeviceBindRecordVos.stream()
|
||||
.map(AppDeviceBindRecordVo::getId)
|
||||
.collect(Collectors.toList());
|
||||
appDeviceBindRecordService.deleteWithValidByIds(ids, true);
|
||||
log.info("删除绑定关系表数据:ids={}",ids);
|
||||
}
|
||||
|
||||
if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
|
||||
// 超级管理员 登出清除动态租户
|
||||
TenantHelper.clearDynamic();
|
||||
|
||||
@ -8,10 +8,19 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLStreamConstants;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
/**
|
||||
* 音频处理服务
|
||||
@ -101,6 +110,12 @@ public class AudioProcessService {
|
||||
// log.info("测试文件已保存: {}", savedPath);
|
||||
// }
|
||||
|
||||
// 保存WAV文件到本地
|
||||
String savedPath = saveByteArrayToFile(pcmData, "tts_output.wav");
|
||||
if (savedPath != null) {
|
||||
log.info("WAV文件已保存: {}", savedPath);
|
||||
}
|
||||
|
||||
// 将byte[]转换为16进制字符串列表
|
||||
List<String> hexList = audioProcessUtil.bytesToHexList(pcmData);
|
||||
|
||||
@ -113,6 +128,55 @@ public class AudioProcessService {
|
||||
}
|
||||
}
|
||||
|
||||
public String saveWavFileLocally(String text, String filename) throws IOException {
|
||||
// 参数校验
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("文本内容不能为空");
|
||||
}
|
||||
|
||||
if (filename == null || filename.trim().isEmpty()) {
|
||||
filename = "tts_output.wav"; // 默认文件名
|
||||
}
|
||||
|
||||
try {
|
||||
// 生成PCM数据
|
||||
byte[] rawPcmData = alibabaTTSUtil.generateStandardPcmData(text);
|
||||
|
||||
// 转换为标准WAV格式(添加44字节头部)
|
||||
byte[] wavData = audioProcessUtil.rawPcmToStandardWav(rawPcmData);
|
||||
|
||||
// 保存到本地文件
|
||||
String filePath = saveByteArrayToFile(wavData, filename);
|
||||
|
||||
log.info("WAV文件已保存: {}", filePath);
|
||||
return filePath;
|
||||
} catch (Exception e) {
|
||||
log.error("保存WAV文件失败: {}", e.getMessage(), e);
|
||||
throw new IOException("保存WAV文件失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String saveByteArrayToFile(byte[] data, String filename) throws IOException {
|
||||
// 确定保存路径(可以是临时目录或指定目录)
|
||||
String directory = System.getProperty("java.io.tmpdir"); // 使用系统临时目录
|
||||
File dir = new File(directory);
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
|
||||
// 创建完整文件路径
|
||||
File file = new File(dir, filename);
|
||||
|
||||
// 写入文件
|
||||
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||
fos.write(data);
|
||||
}
|
||||
|
||||
return file.getAbsolutePath();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 验证音频文件
|
||||
*/
|
||||
@ -170,5 +234,75 @@ public class AudioProcessService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取文本
|
||||
*/
|
||||
public String extract(MultipartFile file) throws Exception {
|
||||
String name = file.getOriginalFilename();
|
||||
if (name == null ||
|
||||
(!name.endsWith(".txt") && !name.endsWith(".docx"))) {
|
||||
throw new IllegalArgumentException("仅支持 .txt 或 .docx");
|
||||
}
|
||||
if (file.getSize() > MAX_AUDIO_SIZE) {
|
||||
throw new IllegalArgumentException("文件超过5MB");
|
||||
}
|
||||
|
||||
String text;
|
||||
/* 全程流式,不落地磁盘,不一次性读字节数组 */
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
if (name.endsWith(".txt")) {
|
||||
text = readTxt(in);
|
||||
} else {
|
||||
text = readDocx(in);
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/* ---------- txt:按行读,StringBuilder 复用 ---------- */
|
||||
private String readTxt(InputStream in) throws IOException {
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
|
||||
StringBuilder sb = new StringBuilder(4096);
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line).append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/* ---------- docx:ZipInputStream 只扫 document.xml ---------- */
|
||||
private String readDocx(InputStream in) throws IOException {
|
||||
ZipInputStream zin = new ZipInputStream(in);
|
||||
ZipEntry e;
|
||||
while ((e = zin.getNextEntry()) != null) {
|
||||
if ("word/document.xml".equals(e.getName())) {
|
||||
return staxExtract(zin); // 流式读 XML
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/* ---------- StAX 流式提取 <w:t> ---------- */
|
||||
private String staxExtract(InputStream xml) throws IOException {
|
||||
XMLStreamReader r = null;
|
||||
StringBuilder sb = new StringBuilder(4096);
|
||||
try {
|
||||
//System.out.println(new String(xml.readAllBytes()));
|
||||
r = XMLInputFactory.newInstance().createXMLStreamReader(xml);
|
||||
while (r.hasNext()) {
|
||||
if (r.next() == XMLStreamConstants.START_ELEMENT &&
|
||||
"t".equals(r.getLocalName())) {
|
||||
String elementText = r.getElementText();
|
||||
sb.append(elementText);
|
||||
}
|
||||
}
|
||||
} catch (XMLStreamException ex) {
|
||||
throw new IOException(ex);
|
||||
} finally {
|
||||
if (r != null) try { r.close(); } catch (XMLStreamException ignore) {}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -28,7 +28,7 @@ public class VideoProcessService {
|
||||
|
||||
private final VideoProcessUtil videoProcessUtil;
|
||||
|
||||
public List<String> processVideo(MultipartFile file) {
|
||||
public List<String> processVideo(MultipartFile file, int code) {
|
||||
// 1. 参数校验
|
||||
validateVideoFile(file);
|
||||
|
||||
@ -39,9 +39,10 @@ public class VideoProcessService {
|
||||
|
||||
// 3. 处理视频并提取帧数据
|
||||
List<String> hexList = videoProcessUtil.processVideoToHex(
|
||||
tempFile, FRAME_RATE, DURATION, WIDTH, HEIGHT
|
||||
tempFile, FRAME_RATE, DURATION, WIDTH, HEIGHT, code
|
||||
);
|
||||
|
||||
log.info("code: {} hexList(前100个): {}", code,
|
||||
hexList.subList(0, Math.min(100, hexList.size())));
|
||||
log.info("视频处理成功,生成Hex数据长度: {}", hexList.size());
|
||||
return hexList;
|
||||
|
||||
|
||||
@ -0,0 +1,48 @@
|
||||
package com.fuyuanshen.global.mqtt.base;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MQTT消息基础模型
|
||||
*/
|
||||
@Data
|
||||
public class MqttMessage {
|
||||
|
||||
/**
|
||||
* 请求ID,用于匹配请求和响应
|
||||
*/
|
||||
private String requestId;
|
||||
|
||||
/**
|
||||
* 设备IMEI
|
||||
*/
|
||||
private String imei;
|
||||
|
||||
/**
|
||||
* 时间戳(毫秒)
|
||||
*/
|
||||
private Long timestamp;
|
||||
|
||||
/**
|
||||
* 功能类型
|
||||
*/
|
||||
private Integer funcType;
|
||||
|
||||
/**
|
||||
* 数据内容
|
||||
*/
|
||||
private Object data;
|
||||
|
||||
/**
|
||||
* 状态(响应时使用)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 批量数据(设备上报时使用)
|
||||
*/
|
||||
private List<SensorData> batch;
|
||||
|
||||
}
|
||||
@ -21,26 +21,31 @@ public class MqttRuleEngine {
|
||||
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
|
||||
|
||||
private final LinkedHashMap<String, MqttMessageRule> rulesMap = new LinkedHashMap<>();
|
||||
|
||||
|
||||
public MqttRuleEngine(List<MqttMessageRule> rules) {
|
||||
// 按优先级排序
|
||||
rules.sort(Comparator.comparing(MqttMessageRule::getPriority));
|
||||
rules.forEach(rule -> rulesMap.put(rule.getCommandType(), rule)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 执行匹配
|
||||
*
|
||||
* @param context 处理上下文
|
||||
* @return
|
||||
*/
|
||||
public boolean executeRule(MqttRuleContext context) {
|
||||
int commandType = context.getCommandType();
|
||||
MqttMessageRule mqttMessageRule = rulesMap.get("Light_"+commandType);
|
||||
MqttMessageRule mqttMessageRule = rulesMap.get("Light_" + commandType);
|
||||
if (mqttMessageRule != null) {
|
||||
threadPoolTaskExecutor.execute(() -> mqttMessageRule.execute(context));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,29 @@
|
||||
package com.fuyuanshen.global.mqtt.base;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* MQTT主题信息模型
|
||||
*/
|
||||
@Data
|
||||
public class MqttTopicInfo {
|
||||
/**
|
||||
* 操作类型 (command/status/report)
|
||||
*/
|
||||
private String operation;
|
||||
|
||||
/**
|
||||
* 租户编码
|
||||
*/
|
||||
private String tenantCode;
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
*/
|
||||
private String deviceType;
|
||||
|
||||
/**
|
||||
* 设备IMEI
|
||||
*/
|
||||
private String imei;
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
package com.fuyuanshen.global.mqtt.base;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 传感器数据模型
|
||||
*/
|
||||
@Data
|
||||
public class SensorData {
|
||||
/**
|
||||
* 传感器名称
|
||||
*/
|
||||
private String sensor;
|
||||
|
||||
/**
|
||||
* 传感器值
|
||||
*/
|
||||
private Object value;
|
||||
|
||||
/**
|
||||
* 时间戳(毫秒)
|
||||
*/
|
||||
private Long timestamp;
|
||||
}
|
||||
@ -3,7 +3,6 @@ package com.fuyuanshen.global.mqtt.constants;
|
||||
|
||||
public interface MqttConstants {
|
||||
|
||||
|
||||
/**
|
||||
* 全局发布消息的key
|
||||
*/
|
||||
@ -13,4 +12,5 @@ public interface MqttConstants {
|
||||
* 全局订阅消息的key
|
||||
*/
|
||||
String GLOBAL_SUB_KEY = "A/";
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,82 @@
|
||||
package com.fuyuanshen.global.mqtt.enums;
|
||||
|
||||
/**
|
||||
* 设备功能类型枚举
|
||||
* 基于AppDeviceBJQ6075Controller中的功能注释1-9设计
|
||||
*/
|
||||
public enum DeviceFunctionType6075 {
|
||||
|
||||
/**
|
||||
* 人员信息登记
|
||||
*/
|
||||
REGISTER_PERSON_INFO(1, "REGISTER_PERSON_INFO", "人员信息登记"),
|
||||
|
||||
/**
|
||||
* 发送信息
|
||||
*/
|
||||
SEND_MESSAGE(2, "SEND_MESSAGE", "发送信息"),
|
||||
|
||||
/**
|
||||
* 发送报警信息
|
||||
*/
|
||||
SEND_ALARM_MESSAGE(3, "SEND_ALARM_MESSAGE", "发送报警信息"),
|
||||
|
||||
/**
|
||||
* 上传设备logo图片
|
||||
*/
|
||||
UPLOAD_LOGO(4, "UPLOAD_LOGO", "上传设备logo图片"),
|
||||
|
||||
/**
|
||||
* 灯光模式(主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
LIGHT_MODE(5, "LIGHT_MODE", "灯光模式"),
|
||||
|
||||
/**
|
||||
* 灯光模式(辅光模式)
|
||||
* 0(关闭灯光),1(泛光),2(泛光爆闪), 3(警示灯), 4(警示灯/泛光)
|
||||
*/
|
||||
AUXILIARY_LIGHT_MODE(6, "AUXILIARY_LIGHT_MODE", "辅光模式"),
|
||||
|
||||
/**
|
||||
* 灯光亮度设置
|
||||
*/
|
||||
LIGHT_BRIGHTNESS(7, "LIGHT_BRIGHTNESS", "灯光亮度设置"),
|
||||
|
||||
/**
|
||||
* 激光模式设置
|
||||
*/
|
||||
LASER_MODE(8, "LASER_MODE", "激光模式设置"),
|
||||
|
||||
/**
|
||||
* 声光报警模式设置
|
||||
*/
|
||||
SOUND_AND_LIGHT_ALARM(9, "SOUND_AND_LIGHT_ALARM", "声光报警模式设置");
|
||||
|
||||
private final int number;
|
||||
private final String code;
|
||||
private final String description;
|
||||
|
||||
DeviceFunctionType6075(int number, String code, String description) {
|
||||
this.number = number;
|
||||
this.code = code;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,136 @@
|
||||
package com.fuyuanshen.global.mqtt.handler;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
|
||||
import com.fuyuanshen.global.mqtt.service.IotMqttService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
/**
|
||||
* IoT设备MQTT消息处理器
|
||||
* 用于处理设备上报的数据和响应消息
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class IotMqttMessageHandler {
|
||||
|
||||
private final IotMqttService iotMqttService;
|
||||
|
||||
/**
|
||||
* 处理MQTT消息
|
||||
*
|
||||
* @param topic 主题
|
||||
* @param payload 消息内容
|
||||
*/
|
||||
public void handleMessage(String topic, String payload) {
|
||||
try {
|
||||
// 解析主题
|
||||
MqttTopicInfo topicInfo = parseTopic(topic);
|
||||
if (topicInfo == null) {
|
||||
log.warn("无法解析MQTT主题: topic={}", topic);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析消息内容
|
||||
JSONObject message = JSON.parseObject(payload);
|
||||
|
||||
// 根据主题类型处理消息
|
||||
switch (topicInfo.getOperation()) {
|
||||
case "command":
|
||||
// 处理下发指令(设备端不会主动发送command类型消息)
|
||||
log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
|
||||
break;
|
||||
case "status":
|
||||
// 处理设备对指令的响应
|
||||
iotMqttService.handleCommandResponse(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
message);
|
||||
break;
|
||||
case "report":
|
||||
// 处理设备主动上报的数据
|
||||
handleDeviceReport(topicInfo, message);
|
||||
break;
|
||||
default:
|
||||
log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析MQTT主题
|
||||
*
|
||||
* @param topic 主题字符串
|
||||
* @return 主题信息对象
|
||||
*/
|
||||
MqttTopicInfo parseTopic(String topic) {
|
||||
if (topic == null || topic.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] parts = topic.split("/");
|
||||
if (parts.length != 4) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MqttTopicInfo info = new MqttTopicInfo();
|
||||
info.setOperation(parts[0]);
|
||||
info.setTenantCode(parts[1]);
|
||||
info.setDeviceType(parts[2]);
|
||||
info.setImei(parts[3]);
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理设备上报数据
|
||||
*
|
||||
* @param topicInfo 主题信息
|
||||
* @param message 消息内容
|
||||
*/
|
||||
private void handleDeviceReport(MqttTopicInfo topicInfo, JSONObject message) {
|
||||
// 获取时间戳
|
||||
Long timestamp = message.getLong("timestamp");
|
||||
|
||||
// 处理批量数据上报
|
||||
if (message.containsKey("batch")) {
|
||||
JSONObject batchData = message.getJSONObject("batch");
|
||||
iotMqttService.handleBatchReport(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
batchData,
|
||||
timestamp);
|
||||
}
|
||||
// 处理单个数据上报
|
||||
else if (message.containsKey("sensor") && message.containsKey("value")) {
|
||||
String sensor = message.getString("sensor");
|
||||
Object value = message.get("value");
|
||||
iotMqttService.handleSingleReport(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
sensor,
|
||||
value,
|
||||
timestamp);
|
||||
}
|
||||
// 处理其他格式的数据
|
||||
else {
|
||||
// 将整个消息作为批量数据处理
|
||||
iotMqttService.handleBatchReport(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
message,
|
||||
timestamp);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
package com.fuyuanshen.global.mqtt.handler;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
import com.fuyuanshen.global.mqtt.service.MqttMessageService;
|
||||
import com.fuyuanshen.global.mqtt.utils.MqttTopicUtils;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* MQTT消息处理器
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MqttMessageHandler {
|
||||
|
||||
private final MqttMessageService mqttMessageService;
|
||||
|
||||
|
||||
/**
|
||||
* 处理MQTT消息
|
||||
* @param topic 主题
|
||||
* @param payload 消息内容
|
||||
*/
|
||||
public void handleMessage(String topic, String payload) {
|
||||
try {
|
||||
// 解析主题
|
||||
MqttTopicInfo topicInfo = MqttTopicUtils.parseTopic(topic);
|
||||
if (topicInfo == null) {
|
||||
log.warn("无法解析MQTT主题: topic={}", topic);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析消息内容
|
||||
MqttMessage message = JSON.parseObject(payload, MqttMessage.class);
|
||||
|
||||
// 根据主题类型处理消息
|
||||
switch (topicInfo.getOperation()) {
|
||||
case "command":
|
||||
// 处理下发指令(设备端不会主动发送command类型消息)
|
||||
log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
|
||||
break;
|
||||
case "status":
|
||||
// 处理设备对指令的响应
|
||||
mqttMessageService.handleCommandResponse(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
message);
|
||||
break;
|
||||
case "report":
|
||||
// 处理设备主动上报的数据
|
||||
mqttMessageService.handleDeviceReport(
|
||||
topicInfo.getTenantCode(),
|
||||
topicInfo.getDeviceType(),
|
||||
topicInfo.getImei(),
|
||||
message);
|
||||
break;
|
||||
default:
|
||||
log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,279 @@
|
||||
package com.fuyuanshen.global.mqtt.receiver;
|
||||
|
||||
import cn.hutool.core.lang.Dict;
|
||||
import com.fuyuanshen.common.core.constant.GlobalConstants;
|
||||
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
|
||||
import com.fuyuanshen.common.json.utils.JsonUtils;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttRuleEngine;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttXinghanCommandType;
|
||||
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
|
||||
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
import org.springframework.messaging.MessageHeaders;
|
||||
import org.springframework.messaging.MessagingException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;
|
||||
|
||||
/**
|
||||
* 6075
|
||||
*
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-11-05 17:41
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class DeviceMessageHandler implements MessageHandler {
|
||||
|
||||
@Autowired
|
||||
private MqttRuleEngine ruleEngine;
|
||||
|
||||
|
||||
@Override
|
||||
public void handleMessage(Message<?> message) throws MessagingException {
|
||||
Object payload = message.getPayload();
|
||||
MessageHeaders headers = message.getHeaders();
|
||||
String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();
|
||||
String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
|
||||
String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
|
||||
|
||||
log.info("MQTT payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
|
||||
payload, receivedTopic, receivedQos, timestamp);
|
||||
|
||||
Dict payloadDict = JsonUtils.parseMap(payload.toString());
|
||||
if (receivedTopic == null || payloadDict == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析设备IMEI
|
||||
String[] subStr = receivedTopic.split("/");
|
||||
String deviceImei = subStr[1];
|
||||
|
||||
// 处理设备在线状态
|
||||
handleDeviceOnlineStatus(deviceImei);
|
||||
|
||||
// 处理不同类型的设备信息
|
||||
processDeviceInformation(payloadDict, deviceImei);
|
||||
|
||||
// 执行规则引擎处理
|
||||
executeRuleEngine(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理设备在线状态
|
||||
*/
|
||||
private void handleDeviceOnlineStatus(String deviceImei) {
|
||||
if (StringUtils.isNotBlank(deviceImei)) {
|
||||
// 添加去重队列
|
||||
String queueKey = MqttMessageQueueConstants.MQTT_MESSAGE_QUEUE_KEY;
|
||||
String dedupKey = MqttMessageQueueConstants.MQTT_MESSAGE_DEDUP_KEY;
|
||||
RedisUtils.offerDeduplicated(queueKey, dedupKey, deviceImei, Duration.ofSeconds(900));
|
||||
|
||||
// 设置设备在线状态
|
||||
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY +
|
||||
DEVICE_KEY_PREFIX + deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
|
||||
RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(360));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理不同类型的设备信息
|
||||
*/
|
||||
private void processDeviceInformation(Dict payloadDict, String deviceImei) {
|
||||
// 开机画面
|
||||
if (payloadDict.containsKey("bootScreen")) {
|
||||
handleBootScreen(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 人员信息
|
||||
if (payloadDict.containsKey("personInfo")) {
|
||||
handlePersonInfo(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 设备信息
|
||||
if (payloadDict.containsKey("deviceInfo")) {
|
||||
handleDeviceInfo(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 经纬度
|
||||
if (payloadDict.containsKey("latitude") && payloadDict.containsKey("longitude")) {
|
||||
handleLocation(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 电子地图
|
||||
if (payloadDict.containsKey("mapData")) {
|
||||
handleMapData(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 电池电量
|
||||
if (payloadDict.containsKey("batteryLevel")) {
|
||||
handleBatteryLevel(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 开启/关闭状态
|
||||
if (payloadDict.containsKey("powerState")) {
|
||||
handlePowerState(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 海拔高度
|
||||
if (payloadDict.containsKey("altitude")) {
|
||||
handleAltitude(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 相对高度
|
||||
if (payloadDict.containsKey("relativeHeight")) {
|
||||
handleRelativeHeight(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 群呼/单呼
|
||||
if (payloadDict.containsKey("callType")) {
|
||||
handleCallType(payloadDict, deviceImei);
|
||||
}
|
||||
|
||||
// 文字信息
|
||||
if (payloadDict.containsKey("textMessage")) {
|
||||
handleTextMessage(payloadDict, deviceImei);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理开机画面
|
||||
*/
|
||||
private void handleBootScreen(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的开机画面信息", deviceImei);
|
||||
// 实现具体的开机画面处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理人员信息
|
||||
*/
|
||||
private void handlePersonInfo(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的人员信息", deviceImei);
|
||||
// 实现具体的人员信息处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理设备信息
|
||||
*/
|
||||
private void handleDeviceInfo(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的设备信息", deviceImei);
|
||||
// 实现具体的设备信息处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理位置信息
|
||||
*/
|
||||
private void handleLocation(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的位置信息: 纬度={}, 经度={}",
|
||||
deviceImei, payloadDict.getStr("latitude"), payloadDict.getStr("longitude"));
|
||||
// 实现具体的位置信息处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理电子地图数据
|
||||
*/
|
||||
private void handleMapData(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的电子地图数据", deviceImei);
|
||||
// 实现具体的电子地图数据处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理电池电量
|
||||
*/
|
||||
private void handleBatteryLevel(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的电池电量: {}", deviceImei, payloadDict.getStr("batteryLevel"));
|
||||
// 实现具体的电池电量处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理开关状态
|
||||
*/
|
||||
private void handlePowerState(Dict payloadDict, String deviceImei) {
|
||||
String powerState = payloadDict.getStr("powerState");
|
||||
log.info("处理设备{}的开关状态: {}", deviceImei, powerState);
|
||||
// 实现具体的开关状态处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理海拔高度
|
||||
*/
|
||||
private void handleAltitude(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的海拔高度: {}", deviceImei, payloadDict.getStr("altitude"));
|
||||
// 实现具体的海拔高度处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理相对高度
|
||||
*/
|
||||
private void handleRelativeHeight(Dict payloadDict, String deviceImei) {
|
||||
log.info("处理设备{}的相对高度: {}", deviceImei, payloadDict.getStr("relativeHeight"));
|
||||
// 实现具体的相对高度处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理呼叫类型
|
||||
*/
|
||||
private void handleCallType(Dict payloadDict, String deviceImei) {
|
||||
String callType = payloadDict.getStr("callType");
|
||||
log.info("处理设备{}的呼叫类型: {}", deviceImei, callType);
|
||||
// 实现具体的呼叫类型处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文字信息
|
||||
*/
|
||||
private void handleTextMessage(Dict payloadDict, String deviceImei) {
|
||||
String textMessage = payloadDict.getStr("textMessage");
|
||||
log.info("处理设备{}的文字信息: {}", deviceImei, textMessage);
|
||||
// 实现具体的文字信息处理逻辑
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行规则引擎处理
|
||||
*/
|
||||
private void executeRuleEngine(Dict payloadDict, String deviceImei) {
|
||||
String state = payloadDict.getStr("state");
|
||||
Object[] convertArr = ImageToCArrayConverter.convertByteStringToMixedObjectArray(state);
|
||||
|
||||
if (convertArr.length > 0) {
|
||||
Byte val1 = (Byte) convertArr[0];
|
||||
MqttRuleContext context = new MqttRuleContext();
|
||||
context.setCommandType(val1);
|
||||
context.setConvertArr(convertArr);
|
||||
context.setDeviceImei(deviceImei);
|
||||
context.setPayloadDict(payloadDict);
|
||||
|
||||
boolean ruleExecuted = ruleEngine.executeRule(context);
|
||||
|
||||
if (!ruleExecuted) {
|
||||
log.warn("未找到匹配的规则来处理命令类型: {}", val1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== 追加:根据报文内容识别格式并统一解析 ===== */
|
||||
int intType = MqttXinghanCommandType.computeVirtualCommandType(payloadDict);
|
||||
if (intType > 0) {
|
||||
MqttRuleContext newCtx = new MqttRuleContext();
|
||||
newCtx.setCommandType((byte) intType);
|
||||
newCtx.setDeviceImei(deviceImei);
|
||||
newCtx.setPayloadDict(payloadDict);
|
||||
|
||||
boolean ok = ruleEngine.executeRule(newCtx);
|
||||
if (!ok) {
|
||||
log.warn("新规则引擎未命中, imei={}", deviceImei);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -90,4 +90,5 @@ public class ReceiverMessageHandler implements MessageHandler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,9 +1,18 @@
|
||||
package com.fuyuanshen.global.mqtt.rule.xinghan;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
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.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.common.sse.dto.SseMessageDto;
|
||||
import com.fuyuanshen.common.sse.utils.SseMessageUtils;
|
||||
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.global.mqtt.base.MqttMessageRule;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
|
||||
import com.fuyuanshen.global.mqtt.config.MqttGateway;
|
||||
@ -21,6 +30,8 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
|
||||
@ -40,6 +51,18 @@ public class XinghanSendAlarmMessageRule implements MqttMessageRule {
|
||||
|
||||
private final MqttGateway mqttGateway;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
private final DeviceLogMapper deviceLogMapper;
|
||||
private final DeviceMapper deviceMapper;
|
||||
/**
|
||||
* 设备上行确认消息
|
||||
*/
|
||||
public static final String BREAK_NEWS_CONFIRMATION = "I get it";
|
||||
|
||||
/**
|
||||
* 设备上行成功标记
|
||||
*/
|
||||
public static final String BREAK_NEWS_SUCCESS = "cover!";
|
||||
|
||||
@Override
|
||||
public String getCommandType() {
|
||||
@ -62,9 +85,36 @@ public class XinghanSendAlarmMessageRule implements MqttMessageRule {
|
||||
log.warn("重复消息丢弃 {}", dedupKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. I get it —— 表示用户确认收到消息
|
||||
if (BREAK_NEWS_CONFIRMATION.equalsIgnoreCase(respText)) {
|
||||
var device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("device_imei", ctx.getDeviceImei()));
|
||||
// 使用MyBatis-Plus内置方法查询最新一条紧急通知
|
||||
QueryWrapper<DeviceLog> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("device_id", device.getId())
|
||||
.eq("device_action", "发送紧急通知") // 根据您的表结构调整
|
||||
.orderByDesc("create_time")
|
||||
.last("LIMIT 1");
|
||||
DeviceLog latestLog = deviceLogMapper.selectOne(queryWrapper);
|
||||
log.info("设备 {} 最新紧急通知:{}", ctx.getDeviceImei(), latestLog);
|
||||
if (latestLog == null) {
|
||||
return;
|
||||
}
|
||||
// 更新数据源字段
|
||||
UpdateWrapper<DeviceLog> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", latestLog.getId()) // 条件:ID匹配
|
||||
.set("data_source", "设备已收到通知"); // 要更新的字段
|
||||
deviceLogMapper.update(null, updateWrapper);
|
||||
// 推送SSE消息
|
||||
scheduledExecutorService.schedule(() -> {
|
||||
SseMessageDto dto = new SseMessageDto();
|
||||
dto.setMessage(String.format("%s设备已收到通知!", latestLog.getDeviceName()));
|
||||
dto.setUserIds(List.of(latestLog.getCreateBy()));
|
||||
SseMessageUtils.publishMessage(dto);
|
||||
}, 5, TimeUnit.SECONDS);
|
||||
return;
|
||||
}
|
||||
// 1. cover! —— 成功标记
|
||||
if ("cover!".equalsIgnoreCase(respText)) {
|
||||
if (BREAK_NEWS_SUCCESS.equalsIgnoreCase(respText)) {
|
||||
RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
|
||||
log.info("设备 {} 发送紧急通知完成", ctx.getDeviceImei());
|
||||
return;
|
||||
|
||||
@ -0,0 +1,106 @@
|
||||
package com.fuyuanshen.global.mqtt.service;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
|
||||
/**
|
||||
* 通用IoT设备MQTT协议服务接口
|
||||
* 遵循统一的MQTT通信协议规范
|
||||
*/
|
||||
public interface IotMqttService {
|
||||
|
||||
/**
|
||||
* 构建下发指令主题
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 指令主题
|
||||
*/
|
||||
String buildCommandTopic(String tenantCode, Long deviceType, String imei);
|
||||
|
||||
/**
|
||||
* 构建响应数据主题
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 响应主题
|
||||
*/
|
||||
String buildStatusTopic(String tenantCode, String deviceType, String imei);
|
||||
|
||||
/**
|
||||
* 构建设备上报数据主题
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 上报主题
|
||||
*/
|
||||
String buildReportTopic(String tenantCode, String deviceType, String imei);
|
||||
|
||||
/**
|
||||
* 发送指令到设备
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 指令消息 (JSON格式)
|
||||
*/
|
||||
void sendCommand(String tenantCode, Long deviceType, String imei, MqttMessage message);
|
||||
|
||||
/**
|
||||
* 发送响应消息到设备
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 响应消息 (JSON格式)
|
||||
*/
|
||||
void sendStatus(String tenantCode, String deviceType, String imei, JSONObject message);
|
||||
|
||||
/**
|
||||
* 发送设备上报数据的确认消息
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 确认消息 (JSON格式)
|
||||
*/
|
||||
void sendReportAck(String tenantCode, String deviceType, String imei, JSONObject message);
|
||||
|
||||
/**
|
||||
* 处理设备上报的单个传感器数据
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param sensor 传感器名称
|
||||
* @param value 传感器值
|
||||
* @param timestamp 时间戳
|
||||
*/
|
||||
void handleSingleReport(String tenantCode, String deviceType, String imei,
|
||||
String sensor, Object value, Long timestamp);
|
||||
|
||||
/**
|
||||
* 处理设备上报的批量传感器数据
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param batchData 批量数据
|
||||
* @param timestamp 时间戳
|
||||
*/
|
||||
void handleBatchReport(String tenantCode, String deviceType, String imei,
|
||||
JSONObject batchData, Long timestamp);
|
||||
|
||||
/**
|
||||
* 处理设备对指令的响应
|
||||
*
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 响应消息 (JSON格式)
|
||||
*/
|
||||
void handleCommandResponse(String tenantCode, String deviceType, String imei, JSONObject message);
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
package com.fuyuanshen.global.mqtt.service;
|
||||
|
||||
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
|
||||
/**
|
||||
* MQTT消息处理服务接口
|
||||
*/
|
||||
public interface MqttMessageService {
|
||||
|
||||
/**
|
||||
* 处理下发指令的响应消息
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 响应消息
|
||||
*/
|
||||
void handleCommandResponse(String tenantCode, String deviceType, String imei, MqttMessage message);
|
||||
|
||||
/**
|
||||
* 处理设备主动上报的数据
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 上报消息
|
||||
*/
|
||||
void handleDeviceReport(String tenantCode, String deviceType, String imei, MqttMessage message);
|
||||
|
||||
/**
|
||||
* 发送指令到设备
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 指令消息
|
||||
*/
|
||||
void sendCommand(String tenantCode, String deviceType, String imei, MqttMessage message);
|
||||
}
|
||||
@ -0,0 +1,111 @@
|
||||
package com.fuyuanshen.global.mqtt.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
import com.fuyuanshen.global.mqtt.service.IotMqttService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 通用IoT设备MQTT协议服务实现类
|
||||
* 遵循统一的MQTT通信协议规范
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class IotMqttServiceImpl implements IotMqttService {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
// MQTT主题前缀
|
||||
private static final String COMMAND_PREFIX = "command";
|
||||
private static final String STATUS_PREFIX = "status";
|
||||
private static final String REPORT_PREFIX = "report";
|
||||
|
||||
@Override
|
||||
public String buildCommandTopic(String tenantCode, Long deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", COMMAND_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildStatusTopic(String tenantCode, String deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", STATUS_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String buildReportTopic(String tenantCode, String deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", REPORT_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendCommand(String tenantCode, Long deviceType, String imei, MqttMessage message) {
|
||||
String topic = buildCommandTopic(tenantCode, deviceType, imei);
|
||||
String payload = JSON.toJSONString(message);
|
||||
sendMqttMessage(topic, 1, payload);
|
||||
log.info("发送指令到设备: topic={}, payload={}", topic, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendStatus(String tenantCode, String deviceType, String imei, JSONObject message) {
|
||||
String topic = buildStatusTopic(tenantCode, deviceType, imei);
|
||||
String payload = message.toJSONString();
|
||||
sendMqttMessage(topic, 1, payload);
|
||||
log.info("发送响应消息到设备: topic={}, payload={}", topic, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendReportAck(String tenantCode, String deviceType, String imei, JSONObject message) {
|
||||
String topic = buildReportTopic(tenantCode, deviceType, imei);
|
||||
String payload = message.toJSONString();
|
||||
sendMqttMessage(topic, 1, payload);
|
||||
log.info("发送设备上报数据确认消息: topic={}, payload={}", topic, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleSingleReport(String tenantCode, String deviceType, String imei,
|
||||
String sensor, Object value, Long timestamp) {
|
||||
log.info("处理设备上报的单个传感器数据: tenantCode={}, deviceType={}, imei={}, sensor={}, value={}, timestamp={}",
|
||||
tenantCode, deviceType, imei, sensor, value, timestamp);
|
||||
|
||||
// TODO: 实现具体的业务逻辑,如更新设备状态、存储传感器数据等
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleBatchReport(String tenantCode, String deviceType, String imei,
|
||||
JSONObject batchData, Long timestamp) {
|
||||
log.info("处理设备上报的批量传感器数据: tenantCode={}, deviceType={}, imei={}, batchData={}, timestamp={}",
|
||||
tenantCode, deviceType, imei, JSON.toJSONString(batchData), timestamp);
|
||||
|
||||
// TODO: 实现具体的业务逻辑,如批量更新设备状态、存储传感器数据等
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCommandResponse(String tenantCode, String deviceType, String imei, JSONObject message) {
|
||||
log.info("处理设备对指令的响应: tenantCode={}, deviceType={}, imei={}, message={}",
|
||||
tenantCode, deviceType, imei, JSON.toJSONString(message));
|
||||
|
||||
// TODO: 实现具体的业务逻辑,如更新指令执行状态等
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过反射方式发送MQTT消息
|
||||
*
|
||||
* @param topic 主题
|
||||
* @param qos 服务质量等级
|
||||
* @param payload 消息内容
|
||||
*/
|
||||
private void sendMqttMessage(String topic, int qos, String payload) {
|
||||
try {
|
||||
Object mqttGateway = applicationContext.getBean("mqttGateway");
|
||||
Method sendMethod = mqttGateway.getClass().getMethod("sendMsgToMqtt", String.class, int.class, String.class);
|
||||
sendMethod.invoke(mqttGateway, topic, qos, payload);
|
||||
} catch (Exception e) {
|
||||
log.error("发送MQTT消息失败: topic={}, payload={}", topic, payload, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,163 @@
|
||||
package com.fuyuanshen.global.mqtt.service.impl;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceMapper;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
import com.fuyuanshen.global.mqtt.base.SensorData;
|
||||
import com.fuyuanshen.global.mqtt.config.MqttGateway;
|
||||
import com.fuyuanshen.global.mqtt.service.MqttMessageService;
|
||||
import com.fuyuanshen.global.mqtt.utils.MqttTopicUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* MQTT消息处理服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MqttMessageServiceImpl implements MqttMessageService {
|
||||
|
||||
private final MqttGateway mqttGateway;
|
||||
|
||||
private final DeviceMapper deviceMapper;
|
||||
|
||||
public MqttMessageServiceImpl(MqttGateway mqttGateway, DeviceMapper deviceMapper) {
|
||||
this.mqttGateway = mqttGateway;
|
||||
this.deviceMapper = deviceMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理下发指令的响应消息
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 响应消息
|
||||
*/
|
||||
@Override
|
||||
public void handleCommandResponse(String tenantCode, String deviceType, String imei, MqttMessage message) {
|
||||
log.info("处理设备响应消息: tenantCode={}, deviceType={}, imei={}, message={}",
|
||||
tenantCode, deviceType, imei, JSON.toJSONString(message));
|
||||
|
||||
// 根据requestId更新指令执行状态
|
||||
// TODO: 实现具体的业务逻辑,比如更新指令执行结果等
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理设备主动上报的数据
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 上报消息
|
||||
*/
|
||||
@Override
|
||||
public void handleDeviceReport(String tenantCode, String deviceType, String imei, MqttMessage message) {
|
||||
log.info("处理设备上报数据: tenantCode={}, deviceType={}, imei={}, message={}",
|
||||
tenantCode, deviceType, imei, JSON.toJSONString(message));
|
||||
|
||||
// 查找设备
|
||||
Device device = deviceMapper.selectDeviceByImei(imei);
|
||||
if (device == null) {
|
||||
log.warn("未找到对应设备: imei={}", imei);
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理批量数据上报
|
||||
if (message.getBatch() != null && !message.getBatch().isEmpty()) {
|
||||
for (int i = 0; i < message.getBatch().size(); i++) {
|
||||
processSensorData(device, message.getBatch().get(i));
|
||||
}
|
||||
}
|
||||
// 处理单个数据上报
|
||||
else if (message.getData() != null) {
|
||||
// 如果data是一个SensorData对象,则处理它
|
||||
// 这里可以根据实际的数据结构做相应处理
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送指令到设备
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @param message 指令消息
|
||||
*/
|
||||
@Override
|
||||
public void sendCommand(String tenantCode, String deviceType, String imei, MqttMessage message) {
|
||||
// 构建下发指令主题
|
||||
String topic = MqttTopicUtils.buildCommandTopic(tenantCode, deviceType, imei);
|
||||
|
||||
// 设置时间戳
|
||||
if (message.getTimestamp() == null) {
|
||||
message.setTimestamp(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
// 发送消息到MQTT
|
||||
String payload = JSON.toJSONString(message);
|
||||
mqttGateway.sendMsgToMqtt(topic, 1, payload);
|
||||
|
||||
log.info("发送指令到设备: topic={}, payload={}", topic, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理传感器数据
|
||||
* @param device 设备对象
|
||||
* @param sensorData 传感器数据
|
||||
*/
|
||||
private void processSensorData(Device device, SensorData sensorData) {
|
||||
log.info("处理传感器数据: deviceId={}, sensor={}, value={}",
|
||||
device.getId(), sensorData.getSensor(), sensorData.getValue());
|
||||
|
||||
String sensor = sensorData.getSensor();
|
||||
Object value = sensorData.getValue();
|
||||
|
||||
// 根据不同的传感器类型处理数据
|
||||
switch (sensor) {
|
||||
case "mainLightMode":
|
||||
// 处理主灯模式数据
|
||||
updateDeviceMainLightMode(device, value);
|
||||
break;
|
||||
case "mainLightBrightness":
|
||||
// 处理主灯亮度数据
|
||||
updateDeviceMainLightBrightness(device, value);
|
||||
break;
|
||||
case "batteryPercent":
|
||||
// 处理电池电量数据
|
||||
updateDeviceBatteryPercent(device, value);
|
||||
break;
|
||||
default:
|
||||
log.warn("未知的传感器类型: sensor={}", sensor);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新设备主灯模式
|
||||
* @param device 设备对象
|
||||
* @param value 主灯模式值
|
||||
*/
|
||||
private void updateDeviceMainLightMode(Device device, Object value) {
|
||||
// TODO: 实现具体的业务逻辑
|
||||
log.info("更新设备主灯模式: deviceId={}, value={}", device.getId(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新设备主灯亮度
|
||||
* @param device 设备对象
|
||||
* @param value 主灯亮度值
|
||||
*/
|
||||
private void updateDeviceMainLightBrightness(Device device, Object value) {
|
||||
// TODO: 实现具体的业务逻辑
|
||||
log.info("更新设备主灯亮度: deviceId={}, value={}", device.getId(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新设备电池电量
|
||||
* @param device 设备对象
|
||||
* @param value 电池电量值
|
||||
*/
|
||||
private void updateDeviceBatteryPercent(Device device, Object value) {
|
||||
// TODO: 实现具体的业务逻辑
|
||||
log.info("更新设备电池电量: deviceId={}, value={}", device.getId(), value);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
package com.fuyuanshen.global.mqtt.utils;
|
||||
|
||||
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
|
||||
import lombok.experimental.UtilityClass;
|
||||
|
||||
/**
|
||||
* MQTT主题处理工具类
|
||||
*/
|
||||
@UtilityClass
|
||||
public class MqttTopicUtils {
|
||||
|
||||
public static final String COMMAND_PREFIX = "command";
|
||||
public static final String STATUS_PREFIX = "status";
|
||||
public static final String REPORT_PREFIX = "report";
|
||||
|
||||
/**
|
||||
* 构建下发指令主题
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 主题字符串
|
||||
*/
|
||||
public static String buildCommandTopic(String tenantCode, String deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", COMMAND_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建响应数据主题
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 主题字符串
|
||||
*/
|
||||
public static String buildStatusTopic(String tenantCode, String deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", STATUS_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建设备上报数据主题
|
||||
* @param tenantCode 租户编码
|
||||
* @param deviceType 设备类型
|
||||
* @param imei 设备IMEI
|
||||
* @return 主题字符串
|
||||
*/
|
||||
public static String buildReportTopic(String tenantCode, String deviceType, String imei) {
|
||||
return String.format("%s/%s/%s/%s", REPORT_PREFIX, tenantCode, deviceType, imei);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析MQTT主题
|
||||
* @param topic 主题字符串
|
||||
* @return 主题信息对象
|
||||
*/
|
||||
public static MqttTopicInfo parseTopic(String topic) {
|
||||
if (topic == null || topic.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] parts = topic.split("/");
|
||||
if (parts.length != 4) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MqttTopicInfo info = new MqttTopicInfo();
|
||||
info.setOperation(parts[0]);
|
||||
info.setTenantCode(parts[1]);
|
||||
info.setDeviceType(parts[2]);
|
||||
info.setImei(parts[3]);
|
||||
return info;
|
||||
}
|
||||
}
|
||||
@ -63,10 +63,6 @@ import java.util.Map;
|
||||
@RequestMapping("/mp")
|
||||
public class MPAuthController {
|
||||
|
||||
private final AppLoginService loginService;
|
||||
private final SysRegisterService registerService;
|
||||
private final ISysConfigService configService;
|
||||
private final ISysTenantService tenantService;
|
||||
private final ISysClientService clientService;
|
||||
private final MPAuthService mpAuthService;
|
||||
private final MPService mpService;
|
||||
@ -74,7 +70,7 @@ public class MPAuthController {
|
||||
|
||||
@Operation(summary = "小程序登录授权")
|
||||
@PostMapping(value = "/login")
|
||||
public ResponseEntity<Object> login(@RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
|
||||
public ResponseEntity<Object> login(@RequestBody AuthUserDto authUser) throws Exception {
|
||||
|
||||
Long phoneNumber = authUser.getPhoneNumber();
|
||||
// 判断小程序用户是否存在,不存在创建
|
||||
|
||||
@ -60,9 +60,9 @@ import java.util.function.Supplier;
|
||||
@Service
|
||||
public class MPAuthService {
|
||||
|
||||
private final ISysUserService userService;
|
||||
private final AppUserService appUserService;
|
||||
|
||||
|
||||
/**
|
||||
* 小程序注册
|
||||
*/
|
||||
@ -128,6 +128,7 @@ public class MPAuthService {
|
||||
return loginVo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构建登录用户
|
||||
*/
|
||||
@ -160,5 +161,4 @@ public class MPAuthService {
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -10,11 +10,8 @@ import org.springframework.stereotype.Service;
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
|
||||
public interface MPService {
|
||||
|
||||
|
||||
/**
|
||||
* 获取小程序用户信息
|
||||
*
|
||||
@ -23,4 +20,5 @@ public interface MPService {
|
||||
UserApp getMpUser(Long phoneNumber);
|
||||
|
||||
UserApp loadUserByUsername(String username);
|
||||
|
||||
}
|
||||
|
||||
@ -8,5 +8,4 @@ package com.fuyuanshen.mp.service.impl;
|
||||
|
||||
public class MPAuthServiceImpl {
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -19,11 +19,9 @@ import org.springframework.stereotype.Service;
|
||||
@RequiredArgsConstructor
|
||||
public class MPServiceImpl implements MPService {
|
||||
|
||||
|
||||
private final AppUserService appUserService;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取小程序用户信息
|
||||
*
|
||||
|
||||
@ -51,6 +51,7 @@ public class CaptchaController {
|
||||
private final CaptchaProperties captchaProperties;
|
||||
private final MailProperties mailProperties;
|
||||
|
||||
|
||||
/**
|
||||
* 短信验证码
|
||||
*
|
||||
|
||||
@ -28,6 +28,7 @@ public class DeviceBJQController extends BaseController {
|
||||
|
||||
private final DeviceBJQBizService appDeviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
@ -35,10 +36,11 @@ public class DeviceBJQController extends BaseController {
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记
|
||||
*/
|
||||
@ -74,7 +76,7 @@ public class DeviceBJQController extends BaseController {
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if(file.getSize()>1024*1024*2){
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService.uploadDeviceLogo(bo);
|
||||
@ -90,7 +92,7 @@ public class DeviceBJQController extends BaseController {
|
||||
public R<Void> batchUploadLogo(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if(file.getSize()>1024*1024*2){
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService.batchUploadLogo(bo);
|
||||
@ -112,7 +114,6 @@ public class DeviceBJQController extends BaseController {
|
||||
|
||||
/**
|
||||
* 灯光亮度设置
|
||||
*
|
||||
*/
|
||||
// @FunctionAccessAnnotation("lightBrightnessSettings")
|
||||
@PostMapping("/lightBrightnessSettings")
|
||||
@ -123,7 +124,6 @@ public class DeviceBJQController extends BaseController {
|
||||
|
||||
/**
|
||||
* 激光模式设置
|
||||
*
|
||||
*/
|
||||
@PostMapping("/laserModeSettings")
|
||||
// @FunctionAccessAnnotation("laserModeSettings")
|
||||
|
||||
@ -29,7 +29,7 @@ import java.util.Map;
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/device")
|
||||
public class DeviceControlCenterController extends BaseController {
|
||||
public class DeviceControlCenterController extends BaseController {
|
||||
|
||||
private final DeviceBizService appDeviceService;
|
||||
|
||||
@ -42,6 +42,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
return appDeviceService.queryWebDeviceList(bo, pageQuery);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 绑定设备
|
||||
*/
|
||||
@ -59,6 +60,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
return toAjax(appDeviceService.unBindDevice(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 查询设备类型列表
|
||||
*/
|
||||
@ -68,6 +70,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
return R.ok(typeList);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 重命名设备
|
||||
*
|
||||
@ -100,7 +103,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
*/
|
||||
@GetMapping("/instructionRecord")
|
||||
public TableDataInfo<InstructionRecordVo> getInstructionRecord(InstructionRecordDto dto, PageQuery pageQuery) {
|
||||
return appDeviceService.getInstructionRecord(dto,pageQuery);
|
||||
return appDeviceService.getInstructionRecord(dto, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -111,7 +114,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
pageQuery.setPageNum(1);
|
||||
pageQuery.setPageSize(2000);
|
||||
TableDataInfo<InstructionRecordVo> instructionRecord = appDeviceService.getInstructionRecord(dto, pageQuery);
|
||||
if(instructionRecord.getRows() == null){
|
||||
if (instructionRecord.getRows() == null) {
|
||||
return;
|
||||
}
|
||||
ExcelUtil.exportExcel(instructionRecord.getRows(), "设备操作日志", InstructionRecordVo.class, response);
|
||||
@ -123,7 +126,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
*/
|
||||
@GetMapping("/locationHistory")
|
||||
public TableDataInfo<LocationHistoryVo> getLocationHistory(InstructionRecordDto dto, PageQuery pageQuery) {
|
||||
return appDeviceService.getLocationHistory(dto,pageQuery);
|
||||
return appDeviceService.getLocationHistory(dto, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -134,7 +137,7 @@ public class DeviceControlCenterController extends BaseController {
|
||||
pageQuery.setPageNum(1);
|
||||
pageQuery.setPageSize(2000);
|
||||
TableDataInfo<LocationHistoryVo> result = appDeviceService.getLocationHistory(dto, pageQuery);
|
||||
if(result.getRows() == null){
|
||||
if (result.getRows() == null) {
|
||||
return;
|
||||
}
|
||||
ExcelUtil.exportExcel(result.getRows(), "历史轨迹记录", LocationHistoryVo.class, response);
|
||||
@ -147,4 +150,5 @@ public class DeviceControlCenterController extends BaseController {
|
||||
public R<List<LocationHistoryDetailVo>> getLocationHistoryDetail(Long id) {
|
||||
return R.ok(appDeviceService.getLocationHistoryDetail(id));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -160,4 +160,5 @@ public class DeviceXinghanController extends BaseController {
|
||||
RedisUtils.setCacheObject(versionKey, json, Duration.ofDays(30));
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,140 @@
|
||||
package com.fuyuanshen.web.controller.device.bjq;
|
||||
|
||||
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
|
||||
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
|
||||
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
|
||||
import com.fuyuanshen.app.domain.vo.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;
|
||||
|
||||
/**
|
||||
* web后台:设备控制类
|
||||
* 6075
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/bjq6075/device")
|
||||
public class DeviceBJQ6075Controller extends BaseController {
|
||||
|
||||
private final DeviceBJQBizService appDeviceService;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDeviceDetailVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(appDeviceService.getInfo(id));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 人员信息登记
|
||||
*/
|
||||
@PostMapping(value = "/registerPersonInfo")
|
||||
// @FunctionAccessAnnotation("registerPersonInfo")
|
||||
public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
|
||||
return toAjax(appDeviceService.registerPersonInfo(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送信息
|
||||
*/
|
||||
@PostMapping(value = "/sendMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendMessage", timeOut = 30, batchMaxTimeOut = 40)
|
||||
public R<Void> sendMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService.sendMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送报警信息
|
||||
*/
|
||||
@PostMapping(value = "/sendAlarmMessage")
|
||||
@FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
|
||||
public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
|
||||
return toAjax(appDeviceService.sendAlarmMessage(bo));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传设备logo图片
|
||||
*/
|
||||
@PostMapping("/uploadLogo")
|
||||
@FunctionAccessAnnotation("uploadLogo")
|
||||
public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService.uploadDeviceLogo(bo);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 批量上传设备logo图片
|
||||
*/
|
||||
@PostMapping("/batchUploadLogo")
|
||||
@FunctionAccessAnnotation("batchUploadLogo")
|
||||
public R<Void> batchUploadLogo(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {
|
||||
|
||||
MultipartFile file = bo.getFile();
|
||||
if (file.getSize() > 1024 * 1024 * 2) {
|
||||
return R.warn("图片不能大于2M");
|
||||
}
|
||||
appDeviceService.batchUploadLogo(bo);
|
||||
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 灯光模式
|
||||
* 0(关灯),1(强光模式),2(弱光模式), 3(爆闪模式), 4(泛光模式)
|
||||
*/
|
||||
// @FunctionAccessAnnotation("lightModeSettings")
|
||||
@PostMapping("/lightModeSettings")
|
||||
public R<Void> lightModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
// params 转 JSONObject
|
||||
appDeviceService.lightModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 灯光亮度设置
|
||||
*/
|
||||
// @FunctionAccessAnnotation("lightBrightnessSettings")
|
||||
@PostMapping("/lightBrightnessSettings")
|
||||
public R<Void> lightBrightnessSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService.lightBrightnessSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 激光模式设置
|
||||
*/
|
||||
@PostMapping("/laserModeSettings")
|
||||
// @FunctionAccessAnnotation("laserModeSettings")
|
||||
public R<Void> laserModeSettings(@RequestBody DeviceInstructDto params) {
|
||||
appDeviceService.laserModeSettings(params);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,107 @@
|
||||
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.AppDevice6075DetailVo;
|
||||
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.*;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceType;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
|
||||
import com.fuyuanshen.equipment.enums.LightModeEnum;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
|
||||
import com.fuyuanshen.global.mqtt.config.MqttGateway;
|
||||
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
|
||||
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
|
||||
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.buildArr;
|
||||
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.generateFixedBitmapData;
|
||||
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
|
||||
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
|
||||
|
||||
|
||||
@Service
|
||||
public interface DeviceBJQ6075BizService {
|
||||
|
||||
/**
|
||||
* 获取设备详情
|
||||
*
|
||||
* @param id 设备ID
|
||||
* @return 设备详情
|
||||
*/
|
||||
public AppDevice6075DetailVo getInfo(Long id);
|
||||
|
||||
public int sendMessage(AppDeviceSendMsgBo bo);
|
||||
|
||||
/**
|
||||
* 记录设备操作日志
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param content 日志内容
|
||||
* @param operator 操作人
|
||||
*/
|
||||
public void recordDeviceLog(Long deviceId, String deviceName, String deviceAction, String content, Long operator);
|
||||
|
||||
/**
|
||||
* 注册人员信息
|
||||
*
|
||||
* @param bo 参数
|
||||
* @return 结果
|
||||
*/
|
||||
public boolean registerPersonInfo(AppPersonnelInfoBo bo);
|
||||
|
||||
public void uploadDeviceLogo2(AppDeviceLogoUploadDto bo);
|
||||
|
||||
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo);
|
||||
|
||||
/**
|
||||
* 灯光模式
|
||||
* (主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
public void lightModeSettings(DeviceInstructDto params);
|
||||
|
||||
// 灯光亮度设置
|
||||
public void lightBrightnessSettings(DeviceInstructDto params);
|
||||
|
||||
// 激光模式设置
|
||||
public void laserModeSettings(DeviceInstructDto params);
|
||||
|
||||
public String mapReverseGeocoding(DeviceInstructDto params);
|
||||
|
||||
public int sendAlarmMessage(AppDeviceSendMsgBo bo);
|
||||
|
||||
public void messageSending(String deviceImei);
|
||||
|
||||
public boolean getDeviceStatus(String deviceImei);
|
||||
|
||||
public void batchUploadLogo(AppDeviceLogoUploadDto bo);
|
||||
|
||||
}
|
||||
@ -59,6 +59,7 @@ public class DeviceBJQBizService {
|
||||
private final MqttGateway mqttGateway;
|
||||
private final DeviceLogMapper deviceLogMapper;
|
||||
|
||||
|
||||
public int sendMessage(AppDeviceSendMsgBo bo) {
|
||||
List<Long> deviceIds = bo.getDeviceIds();
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
@ -69,8 +70,8 @@ public class DeviceBJQBizService {
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在" + deviceId);
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource("image/background.png");
|
||||
@ -78,26 +79,26 @@ public class DeviceBJQBizService {
|
||||
|
||||
byte[] largeData = ImageWithTextGenerate.generate160x80ImageWithText2(bo.getSendMsg(), inputStream, 25600);
|
||||
int[] ints = convertHexToDecimal(largeData);
|
||||
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data" , Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
|
||||
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data", Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
|
||||
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data");
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data");
|
||||
|
||||
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
|
||||
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
|
||||
log.info("发送信息第0块数据大小: {} 字节",specificChunk.length);
|
||||
log.info("发送信息第0块数据大小: {} 字节", specificChunk.length);
|
||||
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(6);
|
||||
intData.add(1);
|
||||
ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk),intData);
|
||||
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));
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送信息点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", deviceId)
|
||||
@ -106,10 +107,10 @@ public class DeviceBJQBizService {
|
||||
|
||||
recordDeviceLog(deviceId, device.getDeviceName(), "发送信息", bo.getSendMsg(), AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
log.info("发送信息设备发送信息失败:{}" ,deviceId);
|
||||
log.info("发送信息设备发送信息失败:{}", deviceId);
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
//发送消息
|
||||
// 发送消息
|
||||
messageSending(device.getDeviceImei());
|
||||
}
|
||||
|
||||
@ -119,11 +120,12 @@ public class DeviceBJQBizService {
|
||||
|
||||
/**
|
||||
* 记录设备操作日志
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param content 日志内容
|
||||
* @param content 日志内容
|
||||
* @param operator 操作人
|
||||
*/
|
||||
private void recordDeviceLog(Long deviceId,String deviceName, String deviceAction, String content, Long 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();
|
||||
@ -171,62 +173,62 @@ public class DeviceBJQBizService {
|
||||
AppPersonnelInfoVo personnelInfoVo = MapstructUtils.convert(appPersonnelInfo, AppPersonnelInfoVo.class);
|
||||
vo.setPersonnelInfo(personnelInfoVo);
|
||||
}
|
||||
//设备在线状态
|
||||
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei()+ DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
|
||||
//设备在线状态
|
||||
if("1".equals(onlineStatus)){
|
||||
vo.setOnlineStatus(1);
|
||||
}else if("2".equals(onlineStatus)){
|
||||
vo.setOnlineStatus(2);
|
||||
}else{
|
||||
vo.setOnlineStatus(0);
|
||||
// 设备在线状态
|
||||
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
|
||||
// 设备在线状态
|
||||
if ("1".equals(onlineStatus)) {
|
||||
vo.setOnlineStatus(1);
|
||||
} else if ("2".equals(onlineStatus)) {
|
||||
vo.setOnlineStatus(2);
|
||||
} else {
|
||||
vo.setOnlineStatus(0);
|
||||
}
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX);
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if(StringUtils.isNotBlank(deviceStatus)){
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
|
||||
vo.setMainLightMode(jsonObject.getString("mainLightMode"));
|
||||
vo.setLaserLightMode(jsonObject.getString("laserLightMode"));
|
||||
vo.setBatteryPercentage(jsonObject.getString("batteryPercentage"));
|
||||
vo.setChargeState(jsonObject.getString("chargeState"));
|
||||
vo.setBatteryRemainingTime(jsonObject.getString("batteryRemainingTime"));
|
||||
}else{
|
||||
} else {
|
||||
vo.setBatteryPercentage("0");
|
||||
}
|
||||
|
||||
String lightModeStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_MODE_KEY_PREFIX);
|
||||
String lightModeStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_MODE_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if(StringUtils.isNotBlank(deviceStatus)){
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
vo.setMainLightMode(lightModeStatus);
|
||||
}
|
||||
|
||||
String lightBrightnessStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(lightBrightnessStatus)){
|
||||
String lightBrightnessStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(lightBrightnessStatus)) {
|
||||
vo.setLightBrightness(lightBrightnessStatus);
|
||||
}
|
||||
|
||||
String laserLightMode = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LASER_MODE_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(laserLightMode)){
|
||||
String laserLightMode = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LASER_MODE_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(laserLightMode)) {
|
||||
vo.setLaserLightMode(laserLightMode);
|
||||
}
|
||||
|
||||
// 获取经度纬度
|
||||
String locationKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LOCATION_KEY_PREFIX;
|
||||
String locationKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LOCATION_KEY_PREFIX;
|
||||
String locationInfo = RedisUtils.getCacheObject(locationKey);
|
||||
if(StringUtils.isNotBlank(locationInfo)){
|
||||
if (StringUtils.isNotBlank(locationInfo)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(locationInfo);
|
||||
vo.setLongitude(jsonObject.get("longitude").toString());
|
||||
vo.setLatitude(jsonObject.get("latitude").toString());
|
||||
vo.setAddress((String)jsonObject.get("address"));
|
||||
vo.setAddress((String) jsonObject.get("address"));
|
||||
}
|
||||
|
||||
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ device.getDeviceImei()+ DEVICE_ALARM_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(alarmStatus)){
|
||||
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(alarmStatus)) {
|
||||
vo.setAlarmStatus(alarmStatus);
|
||||
}
|
||||
|
||||
String lightBrightness = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ device.getDeviceImei()+ DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(lightBrightness)){
|
||||
String lightBrightness = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(lightBrightness)) {
|
||||
vo.setLightBrightness(lightBrightness);
|
||||
}
|
||||
|
||||
@ -234,15 +236,14 @@ public class DeviceBJQBizService {
|
||||
}
|
||||
|
||||
|
||||
|
||||
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
|
||||
Long deviceId = bo.getDeviceId();
|
||||
Device deviceObj = deviceMapper.selectById(deviceId);
|
||||
if (deviceObj == null) {
|
||||
throw new RuntimeException("请先将设备入库!!!");
|
||||
}
|
||||
if(getDeviceStatus(deviceObj.getDeviceImei())){
|
||||
throw new ServiceException(deviceObj.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(deviceObj.getDeviceImei())) {
|
||||
throw new ServiceException(deviceObj.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
|
||||
.eq("device_id", deviceId);
|
||||
@ -266,7 +267,7 @@ 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);
|
||||
String logContent = "单位:"+bo.getUnitName()+",职位:"+bo.getPosition()+",姓名:"+bo.getName()+",ID:"+bo.getCode();
|
||||
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);
|
||||
@ -297,6 +298,7 @@ public class DeviceBJQBizService {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void uploadDeviceLogo2(AppDeviceLogoUploadDto bo) {
|
||||
try {
|
||||
Device device = deviceMapper.selectById(bo.getDeviceId());
|
||||
@ -322,25 +324,26 @@ public class DeviceBJQBizService {
|
||||
// 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));
|
||||
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){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
|
||||
try {
|
||||
Device device = deviceMapper.selectById(bo.getDeviceId());
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
// throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
log.info(device.getDeviceName()+",设备已断开连接");
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", device.getDeviceName()+",设备已断开连接", AppLoginHelper.getUserId());
|
||||
log.info(device.getDeviceName() + ",设备已断开连接");
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", device.getDeviceName() + ",设备已断开连接", AppLoginHelper.getUserId());
|
||||
return;
|
||||
}
|
||||
MultipartFile file = bo.getFile();
|
||||
@ -351,9 +354,9 @@ public class DeviceBJQBizService {
|
||||
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));
|
||||
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX, Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
|
||||
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX);
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX);
|
||||
|
||||
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
|
||||
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
|
||||
@ -363,18 +366,18 @@ public class DeviceBJQBizService {
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(3);
|
||||
intData.add(1);
|
||||
ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk),intData);
|
||||
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));
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", "上传开机画面", AppLoginHelper.getUserId());
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
@ -389,13 +392,13 @@ public class DeviceBJQBizService {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if(device == null){
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(1);
|
||||
intData.add(instructValue);
|
||||
@ -404,26 +407,26 @@ public class DeviceBJQBizService {
|
||||
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));
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
LightModeEnum modeEnum = LightModeEnum.getByCode(instructValue);
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "灯光模式", modeEnum!=null?modeEnum.getName():null, AppLoginHelper.getUserId());
|
||||
} catch (Exception e){
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "灯光模式", modeEnum != null ? modeEnum.getName() : null, AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
//灯光亮度设置
|
||||
// 灯光亮度设置
|
||||
public void lightBrightnessSettings(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if(device == null){
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
String instructValue = params.getInstructValue();
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
@ -431,10 +434,10 @@ public class DeviceBJQBizService {
|
||||
String[] values = instructValue.split("\\.");
|
||||
String value1 = values[0];
|
||||
String value2 = values[1];
|
||||
if(StringUtils.isNoneBlank(value1)){
|
||||
if (StringUtils.isNoneBlank(value1)) {
|
||||
intData.add(Integer.parseInt(value1));
|
||||
}
|
||||
if(StringUtils.isNoneBlank(value2)){
|
||||
if (StringUtils.isNoneBlank(value2)) {
|
||||
intData.add(Integer.parseInt(value2));
|
||||
}
|
||||
intData.add(0);
|
||||
@ -442,25 +445,25 @@ public class DeviceBJQBizService {
|
||||
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));
|
||||
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){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
//激光模式设置
|
||||
// 激光模式设置
|
||||
public void laserModeSettings(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if(device == null){
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
@ -471,15 +474,15 @@ public class DeviceBJQBizService {
|
||||
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));
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
// 1代表开启激光灯,此时主灯关闭,主灯控件为关机状态,为0代表关闭激光灯
|
||||
if("1".equals(params.getInstructValue())){
|
||||
if ("1".equals(params.getInstructValue())) {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "开启激光灯", AppLoginHelper.getUserId());
|
||||
}else{
|
||||
} else {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "关闭激光灯", AppLoginHelper.getUserId());
|
||||
}
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
@ -489,7 +492,7 @@ public class DeviceBJQBizService {
|
||||
QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("device_imei", params.getDeviceImei());
|
||||
List<Device> devices = deviceMapper.selectList(queryWrapper);
|
||||
if(ObjectUtils.length( devices) ==0){
|
||||
if (ObjectUtils.length(devices) == 0) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
return RedisUtils.getCacheObject("device:location:" + devices.get(0).getDeviceImei());
|
||||
@ -507,8 +510,8 @@ public class DeviceBJQBizService {
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在" + deviceId);
|
||||
}
|
||||
if(getDeviceStatus(device.getDeviceImei())){
|
||||
throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
try {
|
||||
|
||||
@ -521,39 +524,39 @@ public class DeviceBJQBizService {
|
||||
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));
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", deviceId)
|
||||
.set("send_msg", bo.getSendMsg());
|
||||
deviceMapper.update(updateWrapper);
|
||||
if("0".equals(bo.getInstructValue())){
|
||||
if ("0".equals(bo.getInstructValue())) {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "解除告警信息", "关闭设备", AppLoginHelper.getUserId());
|
||||
}else{
|
||||
} else {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "发送告警信息", bo.getSendMsg(), AppLoginHelper.getUserId());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.info("设备发送告警信息信息失败:{}" ,deviceId);
|
||||
log.info("设备发送告警信息信息失败:{}", deviceId);
|
||||
throw new ServiceException("设备发送告警信息信息失败");
|
||||
}
|
||||
messageSending(device.getDeviceImei());
|
||||
}
|
||||
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送告警信息指令失败");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private void messageSending(String deviceImei){
|
||||
String sendMessageIng = GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + deviceImei + ":messageSending";
|
||||
private void messageSending(String deviceImei) {
|
||||
String sendMessageIng = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + ":messageSending";
|
||||
RedisUtils.setCacheObject(sendMessageIng, "1", Duration.ofDays(1));
|
||||
}
|
||||
|
||||
private boolean getDeviceStatus(String deviceImei) {
|
||||
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX ;
|
||||
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
|
||||
return RedisUtils.getCacheObject(deviceOnlineStatusRedisKey) == null;
|
||||
}
|
||||
|
||||
@ -571,4 +574,5 @@ public class DeviceBJQBizService {
|
||||
uploadDeviceLogo(dto);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -59,8 +59,8 @@ public class DeviceBizService {
|
||||
private final RealTimeStatusEngine realTimeStatusEngine;
|
||||
private final DeviceLogMapper deviceLogMapper;
|
||||
private final AppDeviceShareMapper appDeviceShareMapper;
|
||||
private final AppUserMapper appUserMapper;;
|
||||
|
||||
private final AppUserMapper appUserMapper;
|
||||
;
|
||||
|
||||
|
||||
public List<APPDeviceTypeVo> getTypeList() {
|
||||
@ -84,37 +84,37 @@ public class DeviceBizService {
|
||||
}
|
||||
Page<AppDeviceVo> result = deviceMapper.queryAppBindDeviceList(pageQuery.build(), bo);
|
||||
List<AppDeviceVo> records = result.getRecords();
|
||||
if(records != null && !records.isEmpty()){
|
||||
if (records != null && !records.isEmpty()) {
|
||||
records.forEach(item -> {
|
||||
if(item.getCommunicationMode()!=null && item.getCommunicationMode() == 0){
|
||||
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("1".equals(onlineStatus)){
|
||||
// 设备在线状态
|
||||
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
|
||||
if ("1".equals(onlineStatus)) {
|
||||
item.setOnlineStatus(1);
|
||||
}else if("2".equals(onlineStatus)){
|
||||
} else if ("2".equals(onlineStatus)) {
|
||||
item.setOnlineStatus(2);
|
||||
}else{
|
||||
} else {
|
||||
item.setOnlineStatus(0);
|
||||
}
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX+ item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if(StringUtils.isNotBlank(deviceStatus)){
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
|
||||
item.setBattery(jsonObject.getString("batteryPercentage"));
|
||||
}else{
|
||||
} else {
|
||||
item.setBattery("0");
|
||||
}
|
||||
|
||||
String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ item.getDeviceImei()+ DEVICE_LOCATION_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(location)){
|
||||
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)){
|
||||
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(alarmStatus)) {
|
||||
item.setAlarmStatus(alarmStatus);
|
||||
}
|
||||
}
|
||||
@ -126,11 +126,11 @@ public class DeviceBizService {
|
||||
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()){
|
||||
if (records != null && !records.isEmpty()) {
|
||||
records.forEach(item -> {
|
||||
if(item.getCommunicationMode()!=null && Ints.asList(0, 2).contains(item.getCommunicationMode())){
|
||||
if (item.getCommunicationMode() != null && Ints.asList(0, 2).contains(item.getCommunicationMode())) {
|
||||
|
||||
//设备在线状态
|
||||
// 设备在线状态
|
||||
// String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ item.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
|
||||
// if("1".equals(onlineStatus)){
|
||||
// item.setOnlineStatus(1);
|
||||
@ -139,24 +139,24 @@ public class DeviceBizService {
|
||||
// }else{
|
||||
// item.setOnlineStatus(0);
|
||||
// }
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX+ item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_STATUS_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if(StringUtils.isNotBlank(deviceStatus)){
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
|
||||
item.setBattery(jsonObject.getString("batteryPercentage"));
|
||||
}else{
|
||||
} else {
|
||||
item.setBattery("0");
|
||||
}
|
||||
|
||||
String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY +DEVICE_KEY_PREFIX+ item.getDeviceImei()+ DEVICE_LOCATION_KEY_PREFIX);
|
||||
if(StringUtils.isNotBlank(location)){
|
||||
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)){
|
||||
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + item.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(alarmStatus)) {
|
||||
item.setAlarmStatus(alarmStatus);
|
||||
}
|
||||
}
|
||||
@ -165,6 +165,7 @@ public class DeviceBizService {
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
|
||||
public int bindDevice(AppDeviceBo bo) {
|
||||
Integer mode = bo.getCommunicationMode();
|
||||
Long userId = AppLoginHelper.getUserId();
|
||||
@ -274,7 +275,7 @@ public class DeviceBizService {
|
||||
if (count == 0) {
|
||||
throw new RuntimeException("请先绑定设备!!!");
|
||||
}
|
||||
if(count<2){
|
||||
if (count < 2) {
|
||||
UpdateWrapper<Device> deviceUpdateWrapper = new UpdateWrapper<>();
|
||||
deviceUpdateWrapper.eq("id", device.getId())
|
||||
.set("binding_user_id", null)
|
||||
@ -291,7 +292,7 @@ public class DeviceBizService {
|
||||
appDeviceBindRecordMapper.deleteById(appDeviceBindRecord.getId()));
|
||||
}
|
||||
AppUserVo appUserVo = appUserMapper.selectVoById(userId);
|
||||
if(appUserVo != null){
|
||||
if (appUserVo != null) {
|
||||
QueryWrapper<AppDeviceShare> appDeviceShareQueryWrapper = new QueryWrapper<>();
|
||||
appDeviceShareQueryWrapper.eq("device_id", device.getId());
|
||||
appDeviceShareQueryWrapper.eq("phonenumber", appUserVo.getPhonenumber());
|
||||
@ -301,7 +302,7 @@ public class DeviceBizService {
|
||||
appDeviceShareMapper.deleteById(appDeviceShare.getId()));
|
||||
}
|
||||
}
|
||||
}else{
|
||||
} else {
|
||||
QueryWrapper<AppDeviceBindRecord> bindRecordQueryWrapper = new QueryWrapper<>();
|
||||
bindRecordQueryWrapper.eq("device_id", device.getId());
|
||||
Long count = appDeviceBindRecordMapper.selectCount(bindRecordQueryWrapper);
|
||||
@ -341,7 +342,7 @@ public class DeviceBizService {
|
||||
QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("device_imei", params.getDeviceImei());
|
||||
List<Device> devices = deviceMapper.selectList(queryWrapper);
|
||||
if(ObjectUtils.length( devices) ==0){
|
||||
if (ObjectUtils.length(devices) == 0) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
return RedisUtils.getCacheObject("device:location:" + devices.get(0).getDeviceImei());
|
||||
@ -350,12 +351,12 @@ public class DeviceBizService {
|
||||
public Map<String, Object> getRealTimeStatus(AppRealTimeStatusDto statusDto) {
|
||||
try {
|
||||
// String commandType = statusDto.getTypeName()+"_" + statusDto.getFunctionMode();"FunctionAccessBatchStatusRule"
|
||||
DeviceStatusRule rule = realTimeStatusEngine.getDeviceStatusRule(statusDto.getTypeName());
|
||||
if(rule == null){
|
||||
DeviceStatusRule rule = realTimeStatusEngine.getDeviceStatusRule(statusDto.getTypeName());
|
||||
if (rule == null) {
|
||||
throw new ServiceException("未匹配到处理命令");
|
||||
}
|
||||
return rule.getStatus(statusDto);
|
||||
} catch (Exception e){
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
@ -393,7 +394,7 @@ public class DeviceBizService {
|
||||
long endTime = today.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
|
||||
|
||||
String deviceImei = device.getDeviceImei();
|
||||
String a = GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX+ deviceImei + DEVICE_LOCATION_KEY_PREFIX + ":history";
|
||||
String a = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DEVICE_LOCATION_KEY_PREFIX + ":history";
|
||||
Collection<String> list = RedisUtils.zRangeByScoreDesc(a, startTime, endTime);
|
||||
if (CollectionUtil.isEmpty(list)) {
|
||||
return null;
|
||||
@ -401,12 +402,12 @@ public class DeviceBizService {
|
||||
|
||||
|
||||
Map<String, List<JSONObject>> map = new LinkedHashMap<>();
|
||||
for (String obj : list){
|
||||
for (String obj : list) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(obj);
|
||||
Long timestamp = jsonObject.getLong("timestamp");
|
||||
LocalDate date = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()).toLocalDate();
|
||||
String address = jsonObject.getString("address");
|
||||
if(StringUtils.isBlank( address) || "[]".equals(address)){
|
||||
if (StringUtils.isBlank(address) || "[]".equals(address)) {
|
||||
continue;
|
||||
}
|
||||
if (map.containsKey(date.toString())) {
|
||||
@ -424,7 +425,7 @@ public class DeviceBizService {
|
||||
detailVo.setDate(entry.getKey());
|
||||
detailVo.setDeviceName(device.getDeviceName());
|
||||
detailVo.setStartLocation(entry.getValue().get(0).getString("address"));
|
||||
detailVo.setEndLocation(entry.getValue().get(entry.getValue().size()-1).getString("address"));
|
||||
detailVo.setEndLocation(entry.getValue().get(entry.getValue().size() - 1).getString("address"));
|
||||
String jsonString = JSONArray.toJSONString(entry.getValue());
|
||||
List<Object> strings = JSONArray.parseArray(jsonString);
|
||||
detailVo.setDetailList(strings);
|
||||
|
||||
@ -39,6 +39,7 @@ public class DeviceDebugService {
|
||||
private final IAppBusinessFileService appBusinessFileService;
|
||||
private final IAppOperationVideoService appOperationVideoService;
|
||||
private final DeviceService deviceService;
|
||||
private final FileHashUtil fileHashUtil;
|
||||
|
||||
/**
|
||||
* 文件上传并添加文件信息哈希去重
|
||||
@ -62,26 +63,12 @@ public class DeviceDebugService {
|
||||
Map<String, Long> hash2OssId = new LinkedHashMap<>(files.length);
|
||||
for (MultipartFile file : files) {
|
||||
// 1. 计算文件哈希
|
||||
String hash = FileHashUtil.hash(file);
|
||||
String hash = fileHashUtil.hash(file);
|
||||
|
||||
// 2. 先根据 hash 查库(秒传)
|
||||
SysOssVo exist = sysOssService.selectByHash(hash);
|
||||
Long ossId;
|
||||
if (exist != null) {
|
||||
// 2.1 已存在,直接复用
|
||||
ossId = exist.getOssId();
|
||||
hash2OssId.putIfAbsent(hash, ossId);
|
||||
} else {
|
||||
// 2.2 不存在,真正上传
|
||||
SysOssVo upload = sysOssService.upload(file);
|
||||
if (upload == null) {
|
||||
return false;
|
||||
}
|
||||
ossId = upload.getOssId();
|
||||
hash2OssId.putIfAbsent(hash, ossId);
|
||||
// 2.3 把 hash 写回记录(供下次去重)
|
||||
sysOssService.updateHashById(ossId, hash);
|
||||
}
|
||||
SysOssVo exist = sysOssService.updateHash(file, hash);
|
||||
// 2.1 已存在,直接复用
|
||||
long ossId = exist.getOssId();
|
||||
hash2OssId.putIfAbsent(hash, ossId);
|
||||
}
|
||||
// 4. 组装业务中间表
|
||||
List<AppBusinessFile> bizList = new ArrayList<>(bo.getDeviceIds().length * hash2OssId.size());
|
||||
|
||||
@ -0,0 +1,665 @@
|
||||
package com.fuyuanshen.web.service.impl;
|
||||
|
||||
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.AppDevice6075DetailVo;
|
||||
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.*;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceType;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
|
||||
import com.fuyuanshen.equipment.enums.LightModeEnum;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceLogMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
|
||||
import com.fuyuanshen.global.mqtt.base.MqttMessage;
|
||||
import com.fuyuanshen.global.mqtt.config.MqttGateway;
|
||||
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
|
||||
import com.fuyuanshen.global.mqtt.constants.MqttConstants;
|
||||
import com.fuyuanshen.global.mqtt.enums.DeviceFunctionType6075;
|
||||
import com.fuyuanshen.global.mqtt.service.IotMqttService;
|
||||
import com.fuyuanshen.web.service.device.DeviceBJQ6075BizService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
|
||||
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.buildArr;
|
||||
import static com.fuyuanshen.common.core.utils.Bitmap80x12Generator.generateFixedBitmapData;
|
||||
import static com.fuyuanshen.common.core.utils.ImageToCArrayConverter.convertHexToDecimal;
|
||||
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceBJQ6075BizServiceImpl implements DeviceBJQ6075BizService {
|
||||
|
||||
private final DeviceMapper deviceMapper;
|
||||
private final AppPersonnelInfoMapper appPersonnelInfoMapper;
|
||||
private final AppPersonnelInfoRecordsMapper appPersonnelInfoRecordsMapper;
|
||||
private final DeviceTypeMapper deviceTypeMapper;
|
||||
private final MqttGateway mqttGateway;
|
||||
private final DeviceLogMapper deviceLogMapper;
|
||||
|
||||
private final IotMqttService iotMqttService;
|
||||
|
||||
|
||||
/**
|
||||
* 获取设备详情
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public AppDevice6075DetailVo getInfo(Long id) {
|
||||
Device device = deviceMapper.selectById(id);
|
||||
if (device == null) {
|
||||
throw new RuntimeException("请先将设备入库!!!");
|
||||
}
|
||||
|
||||
AppDevice6075DetailVo vo = new AppDevice6075DetailVo();
|
||||
vo.setDeviceId(device.getId());
|
||||
vo.setDeviceName(device.getDeviceName());
|
||||
vo.setDevicePic(device.getDevicePic());
|
||||
vo.setDeviceImei(device.getDeviceImei());
|
||||
vo.setDeviceMac(device.getDeviceMac());
|
||||
vo.setDeviceStatus(device.getDeviceStatus());
|
||||
DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
|
||||
if (deviceType != null) {
|
||||
vo.setCommunicationMode(Integer.valueOf(deviceType.getCommunicationMode()));
|
||||
vo.setTypeName(deviceType.getTypeName());
|
||||
}
|
||||
vo.setBluetoothName(device.getBluetoothName());
|
||||
|
||||
vo.setSendMsg(device.getSendMsg());
|
||||
|
||||
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
|
||||
.eq("device_id", device.getId());
|
||||
AppPersonnelInfo appPersonnelInfo = appPersonnelInfoMapper.selectOne(qw);
|
||||
if (appPersonnelInfo != null) {
|
||||
AppPersonnelInfoVo personnelInfoVo = MapstructUtils.convert(appPersonnelInfo, AppPersonnelInfoVo.class);
|
||||
vo.setPersonnelInfo(personnelInfoVo);
|
||||
}
|
||||
// 设备在线状态
|
||||
String onlineStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX);
|
||||
// 设备在线状态
|
||||
if ("1".equals(onlineStatus)) {
|
||||
vo.setOnlineStatus(1);
|
||||
} else if ("2".equals(onlineStatus)) {
|
||||
vo.setOnlineStatus(2);
|
||||
} else {
|
||||
vo.setOnlineStatus(0);
|
||||
}
|
||||
String deviceStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_STATUS_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(deviceStatus);
|
||||
vo.setMainLightMode(jsonObject.getString("mainLightMode"));
|
||||
vo.setLaserLightMode(jsonObject.getString("laserLightMode"));
|
||||
vo.setBatteryPercentage(jsonObject.getString("batteryPercentage"));
|
||||
vo.setChargeState(jsonObject.getString("chargeState"));
|
||||
vo.setBatteryRemainingTime(jsonObject.getString("batteryRemainingTime"));
|
||||
} else {
|
||||
vo.setBatteryPercentage("0");
|
||||
}
|
||||
|
||||
String lightModeStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_MODE_KEY_PREFIX);
|
||||
// 获取电量
|
||||
if (StringUtils.isNotBlank(deviceStatus)) {
|
||||
vo.setMainLightMode(lightModeStatus);
|
||||
}
|
||||
|
||||
String lightBrightnessStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(lightBrightnessStatus)) {
|
||||
vo.setLightBrightness(lightBrightnessStatus);
|
||||
}
|
||||
|
||||
String laserLightMode = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LASER_MODE_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(laserLightMode)) {
|
||||
vo.setLaserLightMode(laserLightMode);
|
||||
}
|
||||
|
||||
// 获取经度纬度
|
||||
String locationKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DeviceRedisKeyConstants.DEVICE_LOCATION_KEY_PREFIX;
|
||||
String locationInfo = RedisUtils.getCacheObject(locationKey);
|
||||
if (StringUtils.isNotBlank(locationInfo)) {
|
||||
JSONObject jsonObject = JSONObject.parseObject(locationInfo);
|
||||
vo.setLongitude(jsonObject.get("longitude").toString());
|
||||
vo.setLatitude(jsonObject.get("latitude").toString());
|
||||
vo.setAddress((String) jsonObject.get("address"));
|
||||
}
|
||||
|
||||
String alarmStatus = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(alarmStatus)) {
|
||||
vo.setAlarmStatus(alarmStatus);
|
||||
}
|
||||
|
||||
String lightBrightness = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_LIGHT_BRIGHTNESS_KEY_PREFIX);
|
||||
if (StringUtils.isNotBlank(lightBrightness)) {
|
||||
vo.setLightBrightness(lightBrightness);
|
||||
}
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int sendMessage(AppDeviceSendMsgBo bo) {
|
||||
List<Long> deviceIds = bo.getDeviceIds();
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
throw new ServiceException("请选择设备");
|
||||
}
|
||||
for (Long deviceId : deviceIds) {
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在" + deviceId);
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource("image/background.png");
|
||||
InputStream inputStream = resource.getInputStream();
|
||||
|
||||
byte[] largeData = ImageWithTextGenerate.generate160x80ImageWithText2(bo.getSendMsg(), inputStream, 25600);
|
||||
int[] ints = convertHexToDecimal(largeData);
|
||||
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data", Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
|
||||
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + ":app_send_message_data");
|
||||
|
||||
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
|
||||
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
|
||||
log.info("发送信息第0块数据大小: {} 字节", specificChunk.length);
|
||||
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(6);
|
||||
intData.add(1);
|
||||
ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk), intData);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送信息点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", deviceId)
|
||||
.set("send_msg", bo.getSendMsg());
|
||||
deviceMapper.update(updateWrapper);
|
||||
|
||||
recordDeviceLog(deviceId, device.getDeviceName(), "发送信息", bo.getSendMsg(), AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
log.info("发送信息设备发送信息失败:{}", deviceId);
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
// 发送消息
|
||||
messageSending(device.getDeviceImei());
|
||||
}
|
||||
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录设备操作日志
|
||||
*
|
||||
* @param deviceId 设备ID
|
||||
* @param content 日志内容
|
||||
* @param operator 操作人
|
||||
*/
|
||||
@Override
|
||||
public 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 注册人员信息
|
||||
*
|
||||
* @param bo
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public boolean registerPersonInfo(AppPersonnelInfoBo bo) {
|
||||
Long deviceId = bo.getDeviceId();
|
||||
Device deviceObj = deviceMapper.selectById(deviceId);
|
||||
if (deviceObj == null) {
|
||||
throw new RuntimeException("请先将设备入库!!!");
|
||||
}
|
||||
if (getDeviceStatus(deviceObj.getDeviceImei())) {
|
||||
throw new ServiceException(deviceObj.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
QueryWrapper<AppPersonnelInfo> qw = new QueryWrapper<AppPersonnelInfo>()
|
||||
.eq("device_id", deviceId);
|
||||
List<AppPersonnelInfoVo> appPersonnelInfoVos = appPersonnelInfoMapper.selectVoList(qw);
|
||||
// 生成固定长度的点阵数据
|
||||
byte[] unitName = generateFixedBitmapData(bo.getUnitName(), 120);
|
||||
byte[] position = generateFixedBitmapData(bo.getPosition(), 120);
|
||||
byte[] name = generateFixedBitmapData(bo.getName(), 120);
|
||||
byte[] id = generateFixedBitmapData(bo.getCode(), 120);
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(2);
|
||||
buildArr(convertHexToDecimal(unitName), intData);
|
||||
buildArr(convertHexToDecimal(name), intData);
|
||||
buildArr(convertHexToDecimal(position), intData);
|
||||
buildArr(convertHexToDecimal(id), intData);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + deviceObj.getDeviceImei(), bo);
|
||||
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);
|
||||
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)
|
||||
.set("name", bo.getName())
|
||||
.set("position", bo.getPosition())
|
||||
.set("unit_name", bo.getUnitName())
|
||||
.set("code", bo.getCode());
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
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("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uploadDeviceLogo(AppDeviceLogoUploadDto bo) {
|
||||
try {
|
||||
Device device = deviceMapper.selectById(bo.getDeviceId());
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
// throw new ServiceException(device.getDeviceName()+",设备已断开连接");
|
||||
log.info(device.getDeviceName() + ",设备已断开连接");
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", device.getDeviceName() + ",设备已断开连接", AppLoginHelper.getUserId());
|
||||
return;
|
||||
}
|
||||
MultipartFile file = bo.getFile();
|
||||
|
||||
byte[] largeData = ImageToCArrayConverter.convertImageToCArray(file.getInputStream(), 160, 80, 25600);
|
||||
log.info("长度:" + largeData.length);
|
||||
|
||||
log.info("原始数据大小: {} 字节", largeData.length);
|
||||
|
||||
int[] ints = convertHexToDecimal(largeData);
|
||||
RedisUtils.setCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX, Arrays.toString(ints), Duration.ofSeconds(5 * 60L));
|
||||
|
||||
String data = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + device.getDeviceImei() + DEVICE_BOOT_LOGO_KEY_PREFIX);
|
||||
|
||||
byte[] arr = ImageToCArrayConverter.convertStringToByteArray(data);
|
||||
byte[] specificChunk = ImageToCArrayConverter.getChunk(arr, 0, 512);
|
||||
log.info("第0块数据大小: {} 字节", specificChunk.length);
|
||||
// log.info("第0块数据: {}", Arrays.toString(specificChunk));
|
||||
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(3);
|
||||
intData.add(1);
|
||||
ImageToCArrayConverter.buildArr(convertHexToDecimal(specificChunk), intData);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "上传开机画面", "上传开机画面", AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 灯光模式
|
||||
* (主光模式)
|
||||
* 0(关闭灯光),1(强光),2(超强光), 3(工作光), 4(节能光),5(爆闪),6(SOS)
|
||||
*/
|
||||
@Override
|
||||
public void lightModeSettings(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
|
||||
String deviceImei = device.getDeviceImei();
|
||||
Long deviceType = device.getDeviceType();
|
||||
String tenantCode = device.getTenantId();
|
||||
|
||||
// 构建发送强光模式的MqttMessage对象
|
||||
MqttMessage message = new MqttMessage();
|
||||
message.setRequestId(UUID.randomUUID().toString()); // 生成唯一的请求ID
|
||||
message.setImei(device.getDeviceImei()); // 设备IMEI
|
||||
message.setTimestamp(System.currentTimeMillis()); // 当前时间戳
|
||||
message.setFuncType(DeviceFunctionType6075.LIGHT_MODE.getNumber()); // 功能类型,这里假设为灯光模式
|
||||
|
||||
// 构建数据内容 - 强光模式参数
|
||||
Map<String, Object> lightData = new HashMap<>();
|
||||
lightData.put("mode", 1); // 1表示强光模式
|
||||
lightData.put("type", "mainLight"); // 主灯类型
|
||||
// 可以根据需要添加更多参数
|
||||
lightData.put("brightness", 100); // 亮度设置为100%
|
||||
|
||||
message.setData(lightData);
|
||||
|
||||
// 调用sendCommand方法发送指令
|
||||
iotMqttService.sendCommand(tenantCode, deviceType, deviceImei, message);
|
||||
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(1);
|
||||
intData.add(instructValue);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
LightModeEnum modeEnum = LightModeEnum.getByCode(instructValue);
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "灯光模式", modeEnum != null ? modeEnum.getName() : null, AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
public void lightModeSettings1(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(1);
|
||||
intData.add(instructValue);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
LightModeEnum modeEnum = LightModeEnum.getByCode(instructValue);
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "灯光模式", modeEnum != null ? modeEnum.getName() : null, AppLoginHelper.getUserId());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 灯光亮度设置
|
||||
@Override
|
||||
public void lightBrightnessSettings(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
String instructValue = params.getInstructValue();
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(5);
|
||||
String[] values = instructValue.split("\\.");
|
||||
String value1 = values[0];
|
||||
String value2 = values[1];
|
||||
if (StringUtils.isNoneBlank(value1)) {
|
||||
intData.add(Integer.parseInt(value1));
|
||||
}
|
||||
if (StringUtils.isNoneBlank(value2)) {
|
||||
intData.add(Integer.parseInt(value2));
|
||||
}
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
// 激光模式设置
|
||||
@Override
|
||||
public void laserModeSettings(DeviceInstructDto params) {
|
||||
try {
|
||||
Long deviceId = params.getDeviceId();
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
Integer instructValue = Integer.parseInt(params.getInstructValue());
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(4);
|
||||
intData.add(instructValue);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
// 1代表开启激光灯,此时主灯关闭,主灯控件为关机状态,为0代表关闭激光灯
|
||||
if ("1".equals(params.getInstructValue())) {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "开启激光灯", AppLoginHelper.getUserId());
|
||||
} else {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "激光模式设置", "关闭激光灯", AppLoginHelper.getUserId());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送指令失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String mapReverseGeocoding(DeviceInstructDto params) {
|
||||
QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
|
||||
queryWrapper.eq("device_imei", params.getDeviceImei());
|
||||
List<Device> devices = deviceMapper.selectList(queryWrapper);
|
||||
if (ObjectUtils.length(devices) == 0) {
|
||||
throw new ServiceException("设备不存在");
|
||||
}
|
||||
return RedisUtils.getCacheObject("device:location:" + devices.get(0).getDeviceImei());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int sendAlarmMessage(AppDeviceSendMsgBo bo) {
|
||||
try {
|
||||
List<Long> deviceIds = bo.getDeviceIds();
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
throw new ServiceException("请选择设备");
|
||||
}
|
||||
|
||||
for (Long deviceId : deviceIds) {
|
||||
Device device = deviceMapper.selectById(deviceId);
|
||||
if (device == null) {
|
||||
throw new ServiceException("设备不存在" + deviceId);
|
||||
}
|
||||
if (getDeviceStatus(device.getDeviceImei())) {
|
||||
throw new ServiceException(device.getDeviceName() + ",设备已断开连接");
|
||||
}
|
||||
try {
|
||||
|
||||
ArrayList<Integer> intData = new ArrayList<>();
|
||||
intData.add(7);
|
||||
intData.add(Integer.parseInt(bo.getInstructValue()));
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
intData.add(0);
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("instruct", intData);
|
||||
mqttGateway.sendMsgToMqtt(MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), 1, JSON.toJSONString(map));
|
||||
log.info("发送点阵数据到设备消息=>topic:{},payload:{}", MqttConstants.GLOBAL_PUB_KEY + device.getDeviceImei(), JSON.toJSONString(map));
|
||||
|
||||
UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
|
||||
updateWrapper.eq("id", deviceId)
|
||||
.set("send_msg", bo.getSendMsg());
|
||||
deviceMapper.update(updateWrapper);
|
||||
if ("0".equals(bo.getInstructValue())) {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "解除告警信息", "关闭设备", AppLoginHelper.getUserId());
|
||||
} else {
|
||||
recordDeviceLog(device.getId(), device.getDeviceName(), "发送告警信息", bo.getSendMsg(), AppLoginHelper.getUserId());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.info("设备发送告警信息信息失败:{}", deviceId);
|
||||
throw new ServiceException("设备发送告警信息信息失败");
|
||||
}
|
||||
messageSending(device.getDeviceImei());
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new ServiceException("发送告警信息指令失败");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageSending(String deviceImei) {
|
||||
String sendMessageIng = GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + ":messageSending";
|
||||
RedisUtils.setCacheObject(sendMessageIng, "1", Duration.ofDays(1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getDeviceStatus(String deviceImei) {
|
||||
String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX;
|
||||
return RedisUtils.getCacheObject(deviceOnlineStatusRedisKey) == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void batchUploadLogo(AppDeviceLogoUploadDto bo) {
|
||||
|
||||
List<Long> deviceIds = bo.getDeviceIds();
|
||||
MultipartFile file = bo.getFile();
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
throw new ServiceException("请选择设备");
|
||||
}
|
||||
for (Long deviceId : deviceIds) {
|
||||
AppDeviceLogoUploadDto dto = new AppDeviceLogoUploadDto();
|
||||
dto.setDeviceId(deviceId);
|
||||
dto.setFile(file);
|
||||
uploadDeviceLogo(dto);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -11,6 +11,8 @@ import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@ -37,63 +39,104 @@ public class VideoProcessUtil {
|
||||
/**
|
||||
* 处理视频并转换为Hex字符串列表
|
||||
*/
|
||||
public List<String> processVideoToHex(File videoFile, int frameRate, int duration, int width, int height) throws Exception {
|
||||
public List<String> processVideoToHex(File videoFile, int frameRate, int duration, int width, int height, int code) throws Exception {
|
||||
// 1. 提取视频帧
|
||||
List<BufferedImage> frames = extractFramesFromVideo(videoFile, frameRate, duration, width, height);
|
||||
|
||||
// 2. 转换为RGB565格式
|
||||
byte[] binaryData = convertFramesToRGB565(frames);
|
||||
if (code == 1) {
|
||||
// 1. 转换为RGB565格式
|
||||
byte[] binaryData = convertFramesToRGB565(frames);
|
||||
|
||||
// 3. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
// 2. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
} else {
|
||||
// 1. 转换为BGR565格式
|
||||
byte[] binaryData = convertFramesToBGR565(frames);
|
||||
|
||||
// 新增:直接生成 mp4
|
||||
//bgr565ToMp4(binaryData, width, height, frameRate, "output.mp4");
|
||||
|
||||
// 2. 转换为Hex字符串列表
|
||||
return bytesToHexList(binaryData);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 从视频中提取帧
|
||||
*
|
||||
* @param videoFile 视频文件对象
|
||||
* @param frameRate 每秒提取的帧数(帧率)
|
||||
* @param duration 需要提取的视频时长(秒)
|
||||
* @param width 提取帧的宽度
|
||||
* @param height 提取帧的高度
|
||||
* @return 提取的帧图像列表
|
||||
* @throws Exception 如果在提取过程中发生错误
|
||||
*/
|
||||
private List<BufferedImage> extractFramesFromVideo(File videoFile, int frameRate, int duration, int width, int height) throws Exception {
|
||||
// 初始化帧列表
|
||||
List<BufferedImage> frames = new ArrayList<>();
|
||||
// 计算需要提取的总帧数 = 帧率 × 时长
|
||||
int totalFramesToExtract = frameRate * duration;
|
||||
|
||||
// 使用FFmpegFrameGrabber从视频文件中抓取帧
|
||||
try (FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(videoFile)) {
|
||||
// 启动抓取器
|
||||
grabber.start();
|
||||
|
||||
// 获取视频总帧数
|
||||
long totalFramesInVideo = grabber.getLengthInFrames();
|
||||
// 获取视频帧率,如果获取不到则默认为30fps
|
||||
int fps = (int) Math.round(grabber.getFrameRate());
|
||||
if (fps <= 0) fps = 30;
|
||||
|
||||
// 计算视频总时长(秒)
|
||||
double durationSeconds = (double) totalFramesInVideo / fps;
|
||||
// 检查视频时长是否满足要求
|
||||
if (durationSeconds < duration) {
|
||||
throw new IllegalArgumentException("视频太短,至少需要 " + duration + " 秒");
|
||||
}
|
||||
|
||||
// 计算帧间隔,用于均匀分布提取的帧
|
||||
double frameInterval = (double) totalFramesInVideo / totalFramesToExtract;
|
||||
|
||||
// 循环提取指定数量的帧
|
||||
for (int i = 0; i < totalFramesToExtract; i++) {
|
||||
// 计算目标帧号
|
||||
int targetFrameNumber = (int) Math.round(i * frameInterval);
|
||||
|
||||
// 检查目标帧号是否超出视频范围
|
||||
if (targetFrameNumber >= totalFramesInVideo) {
|
||||
throw new IllegalArgumentException("目标帧超出范围: " + targetFrameNumber);
|
||||
}
|
||||
|
||||
// 设置抓取器到目标帧
|
||||
grabber.setFrameNumber(targetFrameNumber);
|
||||
// 抓取当前帧
|
||||
Frame frame = grabber.grab();
|
||||
|
||||
// 如果成功抓取到帧且帧图像不为空
|
||||
if (frame != null && frame.image != null) {
|
||||
// 将帧转换为BufferedImage并裁剪到指定尺寸
|
||||
BufferedImage bufferedImage = Java2DFrameUtils.toBufferedImage(frame);
|
||||
frames.add(cropImage(bufferedImage, width, height));
|
||||
} else {
|
||||
// 如果无法获取帧则抛出异常
|
||||
throw new IllegalArgumentException("无法获取第 " + targetFrameNumber + "帧");
|
||||
}
|
||||
}
|
||||
|
||||
// 停止抓取器
|
||||
grabber.stop();
|
||||
}
|
||||
|
||||
// 记录提取的帧数
|
||||
log.debug("从视频中提取了 {} 帧", frames.size());
|
||||
// 返回提取的帧列表
|
||||
return frames;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 将所有帧转换为 RGB565 格式字节数组
|
||||
*/
|
||||
@ -110,6 +153,55 @@ public class VideoProcessUtil {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将所有帧转换为 BGR565 格式字节数组
|
||||
*/
|
||||
private byte[] convertFramesToBGR565(List<BufferedImage> frames) throws Exception {
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
|
||||
for (BufferedImage image : frames) {
|
||||
byte[] bgr565Bytes = convertToBGR565(image);
|
||||
byteArrayOutputStream.write(bgr565Bytes);
|
||||
}
|
||||
|
||||
byte[] result = byteArrayOutputStream.toByteArray();
|
||||
log.debug("转换BGR565数据完成,总字节数: {}", result.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将BufferedImage转换为真正的BGR565格式字节数组
|
||||
*/
|
||||
private byte[] convertToBGR565(BufferedImage image) {
|
||||
int width = image.getWidth();
|
||||
int height = image.getHeight();
|
||||
byte[] bgr565Data = new byte[width * height * 2];
|
||||
|
||||
int index = 0;
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int rgb = image.getRGB(x, y);
|
||||
|
||||
// 提取RGB分量
|
||||
int red = (rgb >> 16) & 0xFF;
|
||||
int green = (rgb >> 8) & 0xFF;
|
||||
int blue = rgb & 0xFF;
|
||||
|
||||
int b = (blue >> 3) & 0x1F; // 5位蓝色
|
||||
int g = (green >> 2) & 0x3F; // 6位绿色
|
||||
int r = (red >> 3) & 0x1F; // 5位红色
|
||||
|
||||
// 正确的BGR565组合:红色在高位,蓝色在低位
|
||||
int bgr565 = (b << 11) | (g << 5) | r;
|
||||
|
||||
bgr565Data[index++] = (byte) ((bgr565 >> 8) & 0xFF);
|
||||
// 小端序存储
|
||||
bgr565Data[index++] = (byte) (bgr565 & 0xFF);
|
||||
}
|
||||
}
|
||||
return bgr565Data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为Hex字符串列表
|
||||
*/
|
||||
@ -191,4 +283,76 @@ public class VideoProcessUtil {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 BGR565 字节流直接写成 MP4(H.264)
|
||||
* @param bgr565 完整的 BGR565 裸帧流(每像素 2 字节)
|
||||
* @param width 帧宽
|
||||
* @param height 帧高
|
||||
* @param fps 帧率
|
||||
* @param outMp4 输出 mp4 文件绝对路径
|
||||
* @throws IOException 进程启动 / IO 失败
|
||||
*/
|
||||
public static void bgr565ToMp4(byte[] bgr565,
|
||||
int width,
|
||||
int height,
|
||||
int fps,
|
||||
String outMp4) throws IOException {
|
||||
|
||||
int framePixels = width * height;
|
||||
int frameBytes = framePixels * 2;
|
||||
if (bgr565.length % frameBytes != 0) {
|
||||
throw new IllegalArgumentException("字节数组长度不是整帧");
|
||||
}
|
||||
|
||||
/* 1. 构造 FFmpeg 命令 */
|
||||
String[] cmd = {
|
||||
"ffmpeg",
|
||||
"-y", // 覆盖输出
|
||||
"-f", "rawvideo",
|
||||
"-pixel_format", "bgr24",
|
||||
"-video_size", width + "x" + height,
|
||||
"-framerate", String.valueOf(fps),
|
||||
"-i", "-", // 从 stdin 读
|
||||
"-c:v", "libx264",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-crf", "23", // 画质可自己调
|
||||
outMp4
|
||||
};
|
||||
|
||||
/* 2. 启动进程 */
|
||||
ProcessBuilder pb = new ProcessBuilder(cmd);
|
||||
pb.redirectError(ProcessBuilder.Redirect.INHERIT); // 把 FFmpeg 日志打到控制台
|
||||
Process p = pb.start();
|
||||
try (OutputStream ffmpegIn = p.getOutputStream()) {
|
||||
|
||||
/* 3. 逐帧转换并写入管道 */
|
||||
byte[] bgr24 = new byte[framePixels * 3];
|
||||
for (int off = 0; off < bgr565.length; off += frameBytes) {
|
||||
for (int i = 0, j = 0; i < frameBytes; i += 2, j += 3) {
|
||||
int u = ((bgr565[off + i + 1] & 0xFF) << 8)
|
||||
| (bgr565[off + i] & 0xFF);
|
||||
int b = (u & 0x1F) << 3;
|
||||
int g = ((u >> 5) & 0x3F) << 2;
|
||||
int r = ((u >> 11) & 0x1F) << 3;
|
||||
bgr24[j] = (byte) b;
|
||||
bgr24[j + 1] = (byte) g;
|
||||
bgr24[j + 2] = (byte) r;
|
||||
}
|
||||
ffmpegIn.write(bgr24);
|
||||
}
|
||||
ffmpegIn.flush();
|
||||
}
|
||||
|
||||
/* 4. 等待编码结束 */
|
||||
try {
|
||||
int exit = p.waitFor();
|
||||
if (exit != 0) {
|
||||
throw new IOException("FFmpeg 异常退出,code=" + exit);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("等待 FFmpeg 被中断", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -52,32 +52,32 @@ spring:
|
||||
url: jdbc:mysql://47.120.79.150:3306/fys-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: root
|
||||
password: Jq_123456#
|
||||
# # 从库数据源
|
||||
# slave:
|
||||
# lazy: true
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
# username:
|
||||
# password:
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: jdbc:oracle:thin:@//localhost:1521/XE
|
||||
# username: ROOT
|
||||
# password: root
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
|
||||
# username: root
|
||||
# password: root
|
||||
# sqlserver:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
|
||||
# url: jdbc:sqlserver://localhost:1433;DatabaseName=tempdb;SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true
|
||||
# username: SA
|
||||
# password: root
|
||||
# # 从库数据源
|
||||
# slave:
|
||||
# lazy: true
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
# username:
|
||||
# password:
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: jdbc:oracle:thin:@//localhost:1521/XE
|
||||
# username: ROOT
|
||||
# password: root
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
|
||||
# username: root
|
||||
# password: root
|
||||
# sqlserver:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
|
||||
# url: jdbc:sqlserver://localhost:1433;DatabaseName=tempdb;SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true
|
||||
# username: SA
|
||||
# password: root
|
||||
hikari:
|
||||
# 最大连接池数量
|
||||
maxPoolSize: 20
|
||||
@ -177,12 +177,12 @@ sms:
|
||||
access-key-id: LTAI5tJdDNpZootsPQ5hdELx
|
||||
# 称为accessSecret有些称之为apiSecret
|
||||
access-key-secret: mU4WtffcCXpHPz5tLwQpaGtLsJXONt
|
||||
#模板ID 非必须配置,如果使用sendMessage的快速发送需此配置
|
||||
#模板ID 非必须配置,如果使用sendMessage的快速发送需此配置
|
||||
template-id: SMS_322180518
|
||||
#模板变量 上述模板的变量
|
||||
#模板变量 上述模板的变量
|
||||
templateName: code
|
||||
signature: 湖北星汉研创科技
|
||||
# sdk-app-id: 您的sdkAppId
|
||||
signature: 湖北星汉研创科技
|
||||
# sdk-app-id: 您的sdkAppId
|
||||
config2:
|
||||
# 厂商标识,标定此配置是哪个厂商,详细请看厂商标识介绍部分
|
||||
supplier: tencent
|
||||
@ -210,7 +210,7 @@ justauth:
|
||||
client-id: 449c4*********937************759
|
||||
client-secret: ac7***********1e0************28d
|
||||
redirect-uri: ${justauth.address}/social-callback?source=topiam
|
||||
scopes: [openid, email, phone, profile]
|
||||
scopes: [ openid, email, phone, profile ]
|
||||
qq:
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
@ -276,33 +276,20 @@ justauth:
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
|
||||
|
||||
# 文件存储路径
|
||||
file:
|
||||
mac:
|
||||
path: ~/file/
|
||||
avatar: ~/avatar/
|
||||
linux:
|
||||
path: /home/eladmin/file/
|
||||
avatar: /home/eladmin/avatar/
|
||||
windows:
|
||||
path: C:\eladmin\file\
|
||||
avatar: C:\eladmin\avatar\
|
||||
# 文件大小 /M
|
||||
maxSize: 100
|
||||
avatarMaxSize: 5
|
||||
device:
|
||||
pic: C:\eladmin\file\ #设备图片存储路径
|
||||
ip: http://fuyuanshen.com:81/ #服务器地址
|
||||
app_avatar:
|
||||
pic: C:\eladmin\file\ #设备图片存储路径
|
||||
#ip: http://fuyuanshen.com:81/ #服务器地址
|
||||
ip: https://fuyuanshen.com/ #服务器地址
|
||||
# MQTT配置
|
||||
mqtt:
|
||||
username: admin
|
||||
password: #YtvpSfCNG
|
||||
url: tcp://www.cnxhyc.com:2883
|
||||
password: fys123456
|
||||
url: tcp://47.107.152.87:1883
|
||||
subClientId: fys_subClient
|
||||
subTopic: A/#
|
||||
pubTopic: B/#
|
||||
pubClientId: fys_pubClient
|
||||
subTopic: A/#,status/tenantCode/#,report/tenantCode/#
|
||||
pubTopic: B/#,command/tenantCode/#
|
||||
pubClientId: fys_pubClient
|
||||
|
||||
|
||||
# TTS语音交互配置
|
||||
alibaba:
|
||||
tts:
|
||||
appKey: KTwSUKMrf2olFfjC
|
||||
akId: LTAI5t6RsfCvQh57qojzbEoe
|
||||
akSecret: MTqvK2mXYeCRkl1jVPndiNumyaad0R
|
||||
@ -55,32 +55,32 @@ spring:
|
||||
url: jdbc:mysql://47.120.79.150:3306/fys-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: root
|
||||
password: Jq_123456#
|
||||
# # 从库数据源
|
||||
# slave:
|
||||
# lazy: true
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
# username:
|
||||
# password:
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: jdbc:oracle:thin:@//localhost:1521/XE
|
||||
# username: ROOT
|
||||
# password: root
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
|
||||
# username: root
|
||||
# password: root
|
||||
# sqlserver:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
|
||||
# url: jdbc:sqlserver://localhost:1433;DatabaseName=tempdb;SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true
|
||||
# username: SA
|
||||
# password: root
|
||||
# # 从库数据源
|
||||
# slave:
|
||||
# lazy: true
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.mysql.cj.jdbc.Driver
|
||||
# url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
# username:
|
||||
# password:
|
||||
# oracle:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: oracle.jdbc.OracleDriver
|
||||
# url: jdbc:oracle:thin:@//localhost:1521/XE
|
||||
# username: ROOT
|
||||
# password: root
|
||||
# postgres:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: org.postgresql.Driver
|
||||
# url: jdbc:postgresql://localhost:5432/postgres?useUnicode=true&characterEncoding=utf8&useSSL=true&autoReconnect=true&reWriteBatchedInserts=true
|
||||
# username: root
|
||||
# password: root
|
||||
# sqlserver:
|
||||
# type: ${spring.datasource.type}
|
||||
# driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
|
||||
# url: jdbc:sqlserver://localhost:1433;DatabaseName=tempdb;SelectMethod=cursor;encrypt=false;rewriteBatchedStatements=true
|
||||
# username: SA
|
||||
# password: root
|
||||
hikari:
|
||||
# 最大连接池数量
|
||||
maxPoolSize: 20
|
||||
@ -281,10 +281,10 @@ justauth:
|
||||
mqtt:
|
||||
username: admin
|
||||
password: #YtvpSfCNG
|
||||
url: tcp://47.120.79.150:2883
|
||||
url: tcp://47.120.79.150:3883
|
||||
subClientId: fys_subClient
|
||||
subTopic: A/#,B/#,worker/location/#
|
||||
pubTopic: B/#
|
||||
subTopic: A/#,status/tenantCode/#,report/tenantCode/#
|
||||
pubTopic: B/#,command/tenantCode/#
|
||||
pubClientId: fys_pubClient
|
||||
|
||||
# TTS语音交互配置
|
||||
@ -294,24 +294,3 @@ alibaba:
|
||||
akId: LTAI5t6RsfCvQh57qojzbEoe
|
||||
akSecret: MTqvK2mXYeCRkl1jVPndiNumyaad0R
|
||||
|
||||
# 文件存储路径
|
||||
file:
|
||||
mac:
|
||||
path: ~/file/
|
||||
avatar: ~/avatar/
|
||||
linux:
|
||||
path: /home/eladmin/file/
|
||||
avatar: /home/eladmin/avatar/
|
||||
windows:
|
||||
path: C:\eladmin\file\
|
||||
avatar: C:\eladmin\avatar\
|
||||
# 文件大小 /M
|
||||
maxSize: 100
|
||||
avatarMaxSize: 5
|
||||
device:
|
||||
pic: C:\eladmin\file\ #设备图片存储路径
|
||||
ip: http://fuyuanshen.com:81/ #服务器地址
|
||||
app_avatar:
|
||||
pic: C:\eladmin\file\ #设备图片存储路径
|
||||
#ip: http://fuyuanshen.com:81/ #服务器地址
|
||||
ip: https://fuyuanshen.com/ #服务器地址
|
||||
@ -269,4 +269,4 @@ justauth:
|
||||
server-url: https://demo.gitea.com
|
||||
client-id: 10**********6
|
||||
client-secret: 1f7d08**********5b7**********29e
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
redirect-uri: ${justauth.address}/social-callback?source=gitea
|
||||
@ -69,9 +69,9 @@ spring:
|
||||
servlet:
|
||||
multipart:
|
||||
# 单个文件大小
|
||||
max-file-size: 10MB
|
||||
max-file-size: 100MB
|
||||
# 设置总上传的文件大小
|
||||
max-request-size: 20MB
|
||||
max-request-size: 200MB
|
||||
mvc:
|
||||
# 设置静态资源路径 防止所有请求都去查静态资源
|
||||
static-path-pattern: /static/**
|
||||
|
||||
10
fys-admin/src/main/resources/josn
Normal file
10
fys-admin/src/main/resources/josn
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"requestId": "123456789",
|
||||
"imei": "864865082081523",
|
||||
"timestamp": 1761025080000,
|
||||
"funcType": "1",
|
||||
"data": {
|
||||
"mainLightMode": 1,
|
||||
"mainLightBrightness": 100
|
||||
}
|
||||
}
|
||||
@ -27,14 +27,14 @@ public class Bitmap80x12Generator {
|
||||
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));
|
||||
System.out.println("打印十进制无符号:" + Arrays.toString(ints));
|
||||
// printDecimalData(bitmapData);
|
||||
|
||||
|
||||
// 生成C文件
|
||||
generateCFile(bitmapData, "bitmap_data.c", "chinese_text");
|
||||
}
|
||||
@ -125,7 +125,7 @@ public class Bitmap80x12Generator {
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void buildArr(int[] data,List<Integer> intData){
|
||||
public static void buildArr(int[] data, List<Integer> intData) {
|
||||
for (int datum : data) {
|
||||
intData.add(datum);
|
||||
}
|
||||
@ -133,8 +133,8 @@ public class Bitmap80x12Generator {
|
||||
|
||||
/**
|
||||
* 生成固定长度的点阵数据
|
||||
*
|
||||
* @param text 要转换的文本
|
||||
*
|
||||
* @param text 要转换的文本
|
||||
* @param fixedLength 固定长度(字节)
|
||||
* @return 固定长度的点阵数据
|
||||
*/
|
||||
@ -157,10 +157,11 @@ public class Bitmap80x12Generator {
|
||||
int copyLength = Math.min(rawData.length, fixedLength);
|
||||
System.arraycopy(rawData, 0, result, 0, copyLength);
|
||||
// 剩余部分自动初始化为0
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建文本图像
|
||||
*/
|
||||
@ -185,14 +186,14 @@ public class Bitmap80x12Generator {
|
||||
|
||||
// 获取字体度量
|
||||
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);
|
||||
|
||||
@ -242,6 +243,7 @@ public class Bitmap80x12Generator {
|
||||
return byteListToArray(byteList);
|
||||
}
|
||||
|
||||
|
||||
public static byte[] byteListToArray(List<Byte> byteList) {
|
||||
byte[] result = new byte[byteList.size()];
|
||||
for (int i = 0; i < byteList.size(); i++) {
|
||||
@ -282,7 +284,7 @@ public class Bitmap80x12Generator {
|
||||
}
|
||||
}
|
||||
bitIndex++;
|
||||
|
||||
|
||||
// 如果已经处理完所有像素,则退出
|
||||
if (bitIndex >= width * height) {
|
||||
return image;
|
||||
@ -313,6 +315,7 @@ public class Bitmap80x12Generator {
|
||||
sb.append("\n};");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印十六进制数据
|
||||
*/
|
||||
@ -320,7 +323,7 @@ public class Bitmap80x12Generator {
|
||||
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();
|
||||
@ -348,6 +351,7 @@ public class Bitmap80x12Generator {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static void writeByteArray(FileWriter writer, byte[] data) throws IOException {
|
||||
for (int i = 0; i < data.length; i++) {
|
||||
int value = data[i] & 0xFF;
|
||||
@ -359,4 +363,6 @@ public class Bitmap80x12Generator {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,206 @@
|
||||
package com.fuyuanshen.common.core.utils.file;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* 图片压缩工具类
|
||||
*
|
||||
* @author AprilWind
|
||||
*/
|
||||
@Slf4j
|
||||
public class ImageCompressUtil {
|
||||
|
||||
/**
|
||||
* 默认压缩目标大小(100KB)
|
||||
*/
|
||||
private static final int DEFAULT_COMPRESS_SIZE = 100 * 1024;
|
||||
|
||||
/**
|
||||
* 默认触发压缩的大小(1MB)
|
||||
*/
|
||||
private static final int DEFAULT_TRIGGER_SIZE = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 压缩图片到指定大小以下(默认100KB)
|
||||
*
|
||||
* @param imageData 原始图片数据
|
||||
* @return 压缩后的图片数据
|
||||
*/
|
||||
public static byte[] compressImage(byte[] imageData) {
|
||||
return compressImage(imageData, DEFAULT_COMPRESS_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩图片到指定大小以下
|
||||
*
|
||||
* @param imageData 原始图片数据
|
||||
* @param maxSize 最大大小(字节)
|
||||
* @return 压缩后的图片数据
|
||||
*/
|
||||
public static byte[] compressImage(byte[] imageData, int maxSize) {
|
||||
try {
|
||||
// 如果图片本身小于等于最大大小,直接返回
|
||||
if (imageData.length <= maxSize) {
|
||||
return imageData;
|
||||
}
|
||||
|
||||
// 读取原始图片
|
||||
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
if (originalImage == null) {
|
||||
log.warn("无法读取图片数据");
|
||||
return imageData;
|
||||
}
|
||||
|
||||
// 检查图片是否包含透明度
|
||||
boolean hasAlpha = hasAlpha(originalImage);
|
||||
String formatName = hasAlpha ? "png" : "jpg";
|
||||
|
||||
// 对于小尺寸PNG图片可跳过压缩以保持图像质量
|
||||
if ("png".equals(formatName) && imageData.length <= 2 * maxSize) {
|
||||
log.debug("PNG图片大小适中({} bytes),跳过压缩", imageData.length);
|
||||
return imageData;
|
||||
}
|
||||
|
||||
// 先尝试质量压缩
|
||||
byte[] compressedData = compressImageQuality(originalImage, formatName, 0.8f);
|
||||
|
||||
// 如果质量压缩后仍大于目标大小,则进行尺寸压缩
|
||||
if (compressedData.length > maxSize) {
|
||||
// 计算缩放比例
|
||||
double scale = Math.sqrt((double) maxSize / compressedData.length);
|
||||
scale = Math.max(scale, 0.5); // 最小缩放到原来的一半
|
||||
|
||||
// 尺寸压缩
|
||||
compressedData = compressImageByScale(originalImage, scale, formatName);
|
||||
}
|
||||
|
||||
// 如果压缩后还是太大,继续压缩
|
||||
int attempts = 0;
|
||||
while (compressedData.length > maxSize && attempts < 5) {
|
||||
// 优先降低质量
|
||||
float quality = Math.max(0.1f, 0.8f - attempts * 0.1f);
|
||||
compressedData = compressImageQuality(originalImage, formatName, quality);
|
||||
|
||||
// 如果质量压缩不够,再缩小尺寸
|
||||
if (compressedData.length > maxSize) {
|
||||
double scale = 0.9 - attempts * 0.1; // 逐步缩小尺寸
|
||||
scale = Math.max(scale, 0.5);
|
||||
compressedData = compressImageByScale(originalImage, scale, formatName);
|
||||
}
|
||||
attempts++;
|
||||
}
|
||||
|
||||
log.info("图片压缩完成,原始大小: {} bytes, 压缩后大小: {} bytes, 压缩率: {}%",
|
||||
imageData.length, compressedData.length,
|
||||
String.format("%.2f", (1.0 - (double) compressedData.length / imageData.length) * 100));
|
||||
|
||||
// 如果压缩后反而变大了,则使用原始数据
|
||||
if (compressedData.length >= imageData.length) {
|
||||
log.debug("压缩后数据变大,使用原始数据");
|
||||
return imageData;
|
||||
}
|
||||
|
||||
return compressedData;
|
||||
} catch (Exception e) {
|
||||
log.error("图片压缩失败: {}", e.getMessage(), e);
|
||||
return imageData; // 压缩失败时返回原始数据
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按比例缩放图片
|
||||
*
|
||||
* @param originalImage 原始图片
|
||||
* @param scale 缩放比例
|
||||
* @param formatName 图片格式
|
||||
* @return 缩放后的图片数据
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private static byte[] compressImageByScale(BufferedImage originalImage, double scale, String formatName) throws IOException {
|
||||
int width = (int) (originalImage.getWidth() * scale);
|
||||
int height = (int) (originalImage.getHeight() * scale);
|
||||
|
||||
// 创建缩放后的图片
|
||||
Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = bufferedImage.createGraphics();
|
||||
|
||||
// 绘制缩放后的图片
|
||||
g2d.drawImage(scaledImage, 0, 0, null);
|
||||
g2d.dispose();
|
||||
|
||||
// 输出为指定格式
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(bufferedImage, formatName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按质量压缩图片
|
||||
*
|
||||
* @param originalImage 原始图片
|
||||
* @param formatName 图片格式
|
||||
* @param quality 压缩质量(0.1-1.0)
|
||||
* @return 压缩后的图片数据
|
||||
* @throws IOException IO异常
|
||||
*/
|
||||
private static byte[] compressImageQuality(BufferedImage originalImage, String formatName, float quality) throws IOException {
|
||||
// 创建压缩参数
|
||||
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
|
||||
if (!writers.hasNext()) {
|
||||
log.warn("找不到合适的图片写入器");
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(originalImage, formatName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
ImageWriter writer = writers.next();
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
|
||||
// 设置压缩参数
|
||||
if (param.canWriteCompressed()) {
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(quality);
|
||||
}
|
||||
|
||||
// 写入压缩后的图片数据
|
||||
ByteArrayOutputStream compressedOutputStream = new ByteArrayOutputStream();
|
||||
writer.setOutput(ImageIO.createImageOutputStream(compressedOutputStream));
|
||||
writer.write(null, new javax.imageio.IIOImage(originalImage, null, null), param);
|
||||
writer.dispose();
|
||||
|
||||
return compressedOutputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查图片是否包含透明度
|
||||
*
|
||||
* @param image 图片
|
||||
* @return 是否包含透明度
|
||||
*/
|
||||
private static boolean hasAlpha(BufferedImage image) {
|
||||
return image.getType() == BufferedImage.TYPE_4BYTE_ABGR ||
|
||||
image.getType() == BufferedImage.TYPE_INT_ARGB ||
|
||||
image.getColorModel().hasAlpha();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断图片是否需要压缩(超过1MB)
|
||||
*
|
||||
* @param imageData 图片数据
|
||||
* @return 是否需要压缩
|
||||
*/
|
||||
public static boolean needCompress(byte[] imageData) {
|
||||
return imageData.length > DEFAULT_TRIGGER_SIZE;
|
||||
}
|
||||
}
|
||||
@ -216,4 +216,5 @@ public class LogAspect {
|
||||
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|
||||
|| o instanceof BindingResult;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,79 @@
|
||||
package com.fuyuanshen.app.controller;
|
||||
|
||||
import com.fuyuanshen.app.domain.AppDeviceVoice;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo;
|
||||
import com.fuyuanshen.app.service.IAppDeviceVoiceService;
|
||||
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.core.validate.QueryGroup;
|
||||
import com.fuyuanshen.common.web.core.BaseController;
|
||||
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
|
||||
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 设备语音Controller
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/app/device/voice")
|
||||
public class AppDeviceVoiceController extends BaseController {
|
||||
|
||||
private final IAppDeviceVoiceService appDeviceVoiceService;
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<AppDeviceVoice> list(AppDeviceVoiceBo bo, PageQuery pageQuery) {
|
||||
return appDeviceVoiceService.queryPageList(bo, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取设备语音详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public R<AppDeviceVoice> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
|
||||
return R.ok(appDeviceVoiceService.queryById(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增设备语音
|
||||
*/
|
||||
@PostMapping()
|
||||
public R<Void> add(@RequestPart("bo") @Validated(AddGroup.class) AppDeviceVoiceBo bo,
|
||||
@RequestPart(value = "file", required = false) MultipartFile file) {
|
||||
return toAjax(appDeviceVoiceService.insertByBo(bo, file));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改设备语音
|
||||
*/
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody AppDeviceVoiceBo bo) {
|
||||
return toAjax(appDeviceVoiceService.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除设备语音
|
||||
*
|
||||
* @param ids 主键串
|
||||
*/
|
||||
@DeleteMapping("/{ids}")
|
||||
public R<Void> remove(@NotNull(message = "主键不能为空") @PathVariable Long[] ids) {
|
||||
return toAjax(appDeviceVoiceService.deleteWithValidByIds(Arrays.asList(ids), true));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* 设备语音
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("app_device_voice")
|
||||
public class AppDeviceVoice extends TenantEntity {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键id
|
||||
*/
|
||||
@TableId(value = "id")
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 视频名称
|
||||
*/
|
||||
private String videoName;
|
||||
|
||||
/**
|
||||
* 视频链接
|
||||
*/
|
||||
private String videoUrl;
|
||||
|
||||
/**
|
||||
* 设备di
|
||||
*/
|
||||
private Long deviceId;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 文件类型
|
||||
* audio/mp3, audio/wav 等
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 时长(秒)
|
||||
*/
|
||||
private Integer duration;
|
||||
|
||||
/**
|
||||
* 文件大小(字节)
|
||||
*/
|
||||
private Long size;
|
||||
|
||||
/**
|
||||
* 封面图URL
|
||||
*/
|
||||
private String cover;
|
||||
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
package com.fuyuanshen.app.domain.bo;
|
||||
|
||||
import com.fuyuanshen.common.core.validate.AddGroup;
|
||||
import com.fuyuanshen.common.core.validate.EditGroup;
|
||||
import com.fuyuanshen.common.mybatis.core.domain.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import jakarta.validation.constraints.*;
|
||||
|
||||
/**
|
||||
* 设备语音业务对象 app_device_voice
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class AppDeviceVoiceBo extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键id
|
||||
*/
|
||||
@NotNull(message = "主键id不能为空", groups = { EditGroup.class })
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 视频名称
|
||||
*/
|
||||
@NotBlank(message = "视频名称不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String videoName;
|
||||
|
||||
/**
|
||||
* 视频链接
|
||||
*/
|
||||
@NotBlank(message = "视频链接不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private String videoUrl;
|
||||
|
||||
/**
|
||||
* 设备di
|
||||
*/
|
||||
@NotNull(message = "设备di不能为空", groups = { AddGroup.class, EditGroup.class })
|
||||
private Long deviceId;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 文件类型
|
||||
* audio/mp3, audio/wav 等
|
||||
*/
|
||||
private String type;
|
||||
|
||||
/**
|
||||
* 时长(秒)
|
||||
*/
|
||||
private Integer duration;
|
||||
|
||||
/**
|
||||
* 文件大小(字节)
|
||||
*/
|
||||
private Long size;
|
||||
|
||||
/**
|
||||
* 封面图URL
|
||||
*/
|
||||
private String cover;
|
||||
|
||||
}
|
||||
@ -64,4 +64,5 @@ public class AppPersonnelInfoBo extends BaseEntity {
|
||||
* ID号
|
||||
*/
|
||||
private String code;
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,120 @@
|
||||
package com.fuyuanshen.app.domain.vo;
|
||||
|
||||
import cn.idev.excel.annotation.ExcelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
@Data
|
||||
public class AppDevice6075DetailVo {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 设备ID
|
||||
*/
|
||||
@ExcelProperty(value = "设备ID")
|
||||
private Long deviceId;
|
||||
|
||||
/**
|
||||
* 设备名称
|
||||
*/
|
||||
private String deviceName;
|
||||
|
||||
/**
|
||||
* 设备IMEI
|
||||
*/
|
||||
private String deviceImei;
|
||||
|
||||
/**
|
||||
* 设备MAC
|
||||
*/
|
||||
private String deviceMac;
|
||||
|
||||
/**
|
||||
* 通讯方式 0:4G;1:蓝牙,2 4G&蓝牙
|
||||
*/
|
||||
private Integer communicationMode;
|
||||
|
||||
/**
|
||||
* 设备图片
|
||||
*/
|
||||
private String devicePic;
|
||||
|
||||
/**
|
||||
* 设备类型
|
||||
*/
|
||||
private String typeName;
|
||||
|
||||
/**
|
||||
* 蓝牙名称
|
||||
*/
|
||||
private String bluetoothName;
|
||||
|
||||
/**
|
||||
* 设备状态
|
||||
* 0 失效
|
||||
* 1 正常
|
||||
*/
|
||||
private Integer deviceStatus;
|
||||
|
||||
/**
|
||||
* 人员信息
|
||||
*/
|
||||
private AppPersonnelInfoVo personnelInfo;
|
||||
|
||||
/**
|
||||
* 发送信息
|
||||
*/
|
||||
private String sendMsg;
|
||||
|
||||
//"{\"deviceImei\":\"AA\",\"mainLightMode\":\"1\",\"laserLightMode\":\"0\",\"batteryPercentage\":\"60\",\"chargeState\":\"1\",\"batteryRemainingTime\":\"200\",\"timestamp\":1753871635241}"
|
||||
// 设备主灯档位
|
||||
private String mainLightMode;
|
||||
|
||||
// 激光灯档位
|
||||
private String laserLightMode;
|
||||
|
||||
// 电量百分比
|
||||
private String batteryPercentage;
|
||||
|
||||
// 充电状态(0没有充电,1正在充电,2为已充满)
|
||||
private String chargeState;
|
||||
|
||||
// 电池剩余续航时间200分钟
|
||||
private String batteryRemainingTime;
|
||||
|
||||
/**
|
||||
* 在线状态(0离线,1在线)
|
||||
*/
|
||||
private Integer onlineStatus;
|
||||
|
||||
// 经度
|
||||
private String longitude;
|
||||
|
||||
// 纬度
|
||||
private String latitude;
|
||||
|
||||
// 逆解析地址
|
||||
private String address;
|
||||
|
||||
/**
|
||||
* 告警状态(0解除告警,1告警)
|
||||
*/
|
||||
private String alarmStatus;
|
||||
|
||||
// 灯光亮度
|
||||
private String lightBrightness;
|
||||
|
||||
/**
|
||||
* 海拔高度
|
||||
*/
|
||||
private Double altitude;
|
||||
|
||||
/**
|
||||
* 相对高度
|
||||
*/
|
||||
private Double relativeAltitude;
|
||||
|
||||
}
|
||||
@ -45,8 +45,7 @@ public class AppDeviceShareDetailVo implements Serializable {
|
||||
private String phonenumber;
|
||||
|
||||
/**
|
||||
* 功能权限(1:灯光模式;2:激光模式;3:开机画面;4:人员信息登记;5:发送信息;6:产品信息)
|
||||
以逗号分隔
|
||||
* 功能权限(1:灯光模式;2:激光模式;3:开机画面;4:人员信息登记;5:发送信息;6:产品信息)以逗号分隔
|
||||
*/
|
||||
@ExcelProperty(value = "功能权限", converter = ExcelDictConvert.class)
|
||||
@ExcelDictFormat(readConverterExp = "1=:灯光模式;2:激光模式;3:开机画面;4:人员信息登记;5:发送信息;6:产品信息")
|
||||
@ -83,7 +82,7 @@ public class AppDeviceShareDetailVo implements Serializable {
|
||||
private String typeName;
|
||||
|
||||
/**
|
||||
* 蓝牙名称
|
||||
* 蓝牙名称
|
||||
*/
|
||||
private String bluetoothName;
|
||||
|
||||
@ -105,19 +104,19 @@ public class AppDeviceShareDetailVo implements Serializable {
|
||||
*/
|
||||
private String sendMsg;
|
||||
|
||||
//设备主灯档位
|
||||
// 设备主灯档位
|
||||
private String mainLightMode;
|
||||
|
||||
//激光灯档位
|
||||
// 激光灯档位
|
||||
private String laserLightMode;
|
||||
|
||||
//电量百分比
|
||||
// 电量百分比
|
||||
private String batteryPercentage;
|
||||
|
||||
//充电状态(0没有充电,1正在充电,2为已充满)
|
||||
// 充电状态(0没有充电,1正在充电,2为已充满)
|
||||
private String chargeState;
|
||||
|
||||
//电池剩余续航时间200分钟
|
||||
// 电池剩余续航时间200分钟
|
||||
private String batteryRemainingTime;
|
||||
|
||||
/**
|
||||
|
||||
@ -64,5 +64,4 @@ public class AppPersonnelInfoVo implements Serializable {
|
||||
@ExcelProperty(value = "ID号")
|
||||
private String code;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,52 @@
|
||||
package com.fuyuanshen.app.domain.vo;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) throws IOException {
|
||||
|
||||
String[] availableIDs = TimeZone.getAvailableIDs();
|
||||
for (String id : availableIDs) {
|
||||
System.out.println(id);
|
||||
}
|
||||
|
||||
byte[] data = "hello, world!".getBytes(StandardCharsets.UTF_8);
|
||||
try (CountInputStream input = new CountInputStream(new ByteArrayInputStream(data))) {
|
||||
int n;
|
||||
while ((n = input.read()) != -1) {
|
||||
System.out.println((char)n);
|
||||
}
|
||||
System.out.println("Total read " + input.getBytesRead() + " bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CountInputStream extends FilterInputStream {
|
||||
private int count = 0;
|
||||
|
||||
CountInputStream(InputStream in) {
|
||||
super(in);
|
||||
}
|
||||
|
||||
public int getBytesRead() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
public int read() throws IOException {
|
||||
int n = in.read();
|
||||
if (n != -1) {
|
||||
this.count ++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
int n = in.read(b, off, len);
|
||||
if (n != -1) {
|
||||
this.count += n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,8 @@ import com.fuyuanshen.app.domain.vo.AppDeviceShareVo;
|
||||
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备分享Mapper接口
|
||||
*
|
||||
@ -27,4 +29,6 @@ public interface AppDeviceShareMapper extends BaseMapperPlus<AppDeviceShare, App
|
||||
* @return 设备分享
|
||||
*/
|
||||
Page<AppDeviceShareVo> selectWebDeviceShareList(@Param("bo") AppDeviceShareBo bo, Page<AppDeviceShareVo> page);
|
||||
|
||||
void deleteByDeviceIds(@Param("deviceIds") List<Long> deviceIds);
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
package com.fuyuanshen.app.mapper;
|
||||
|
||||
import com.fuyuanshen.app.domain.AppDeviceVoice;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo;
|
||||
import com.fuyuanshen.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备语音Mapper接口
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
public interface AppDeviceVoiceMapper extends BaseMapperPlus<AppDeviceVoice, AppDeviceVoice> {
|
||||
|
||||
/**
|
||||
* 分页查询设备语音列表
|
||||
*/
|
||||
Page<AppDeviceVoice> selectPage(AppDeviceVoiceBo bo, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
List<AppDeviceVoice> selectList(AppDeviceVoiceBo bo);
|
||||
|
||||
}
|
||||
@ -67,4 +67,6 @@ public interface IAppDeviceShareService {
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
|
||||
TableDataInfo<AppDeviceShareVo> otherDeviceShareList(AppDeviceShareBo bo, PageQuery pageQuery);
|
||||
|
||||
void deleteByDeviceIds(List<Long> deviceIds);
|
||||
}
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
package com.fuyuanshen.app.service;
|
||||
|
||||
import com.fuyuanshen.app.domain.AppDeviceVoice;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo;
|
||||
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
|
||||
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备语音Service接口
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
public interface IAppDeviceVoiceService {
|
||||
|
||||
/**
|
||||
* 查询设备语音
|
||||
*/
|
||||
AppDeviceVoice queryById(Long id);
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
TableDataInfo<AppDeviceVoice> queryPageList(AppDeviceVoiceBo bo, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
List<AppDeviceVoice> queryList(AppDeviceVoiceBo bo);
|
||||
|
||||
/**
|
||||
* 根据新增业务对象插入设备语音
|
||||
*/
|
||||
Boolean insertByBo(AppDeviceVoiceBo bo, MultipartFile file);
|
||||
|
||||
/**
|
||||
* 根据编辑业务对象更新设备语音
|
||||
*/
|
||||
Boolean updateByBo(AppDeviceVoiceBo bo);
|
||||
|
||||
/**
|
||||
* 校验并批量删除设备语音信息
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
}
|
||||
@ -166,4 +166,9 @@ public class AppDeviceShareServiceImpl implements IAppDeviceShareService {
|
||||
});
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteByDeviceIds(List<Long> deviceIds) {
|
||||
baseMapper.deleteByDeviceIds(deviceIds);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,130 @@
|
||||
package com.fuyuanshen.app.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fuyuanshen.app.domain.AppDeviceVoice;
|
||||
import com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo;
|
||||
import com.fuyuanshen.app.mapper.AppDeviceVoiceMapper;
|
||||
import com.fuyuanshen.app.service.IAppDeviceVoiceService;
|
||||
import com.fuyuanshen.common.core.utils.StringUtils;
|
||||
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
|
||||
import com.fuyuanshen.common.mybatis.core.page.PageQuery;
|
||||
import com.fuyuanshen.common.oss.core.OssClient;
|
||||
import com.fuyuanshen.common.oss.entity.UploadResult;
|
||||
import com.fuyuanshen.common.oss.factory.OssFactory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备语音Service业务层处理
|
||||
*
|
||||
* @author Lion Li
|
||||
* @date 2025-07-02
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class AppDeviceVoiceServiceImpl implements IAppDeviceVoiceService {
|
||||
|
||||
private final AppDeviceVoiceMapper baseMapper;
|
||||
|
||||
/**
|
||||
* 查询设备语音
|
||||
*/
|
||||
@Override
|
||||
public AppDeviceVoice queryById(Long id) {
|
||||
return baseMapper.selectById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
@Override
|
||||
public TableDataInfo<AppDeviceVoice> queryPageList(AppDeviceVoiceBo bo, PageQuery pageQuery) {
|
||||
Page<AppDeviceVoice> page = baseMapper.selectPage(bo, pageQuery);
|
||||
return TableDataInfo.build(page);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询设备语音列表
|
||||
*/
|
||||
@Override
|
||||
public List<AppDeviceVoice> queryList(AppDeviceVoiceBo bo) {
|
||||
return baseMapper.selectList(bo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据新增业务对象插入设备语音
|
||||
*/
|
||||
@Override
|
||||
public Boolean insertByBo(AppDeviceVoiceBo bo, MultipartFile file) {
|
||||
// 上传文件到MinIO
|
||||
String videoUrl = "";
|
||||
String coverUrl = "";
|
||||
Long size = 0L;
|
||||
Integer duration = 0;
|
||||
String type = "";
|
||||
|
||||
if (file != null && !file.isEmpty()) {
|
||||
try {
|
||||
OssClient storage = OssFactory.instance();
|
||||
String suffix = "";
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
if (originalFilename != null && originalFilename.lastIndexOf(".") > 0) {
|
||||
suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
}
|
||||
UploadResult result = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
|
||||
videoUrl = result.getUrl();
|
||||
size = file.getSize();
|
||||
type = file.getContentType();
|
||||
// TODO: 可以通过其他方式获取音频时长,这里暂时设置为默认值
|
||||
duration = 0;
|
||||
// TODO: 可以生成封面图,这里暂时设置为空
|
||||
coverUrl = "";
|
||||
} catch (Exception e) {
|
||||
// 文件上传失败处理
|
||||
throw new RuntimeException("文件上传失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
AppDeviceVoice add = new AppDeviceVoice();
|
||||
add.setVideoName(bo.getVideoName());
|
||||
add.setVideoUrl(videoUrl);
|
||||
add.setDeviceId(bo.getDeviceId());
|
||||
add.setRemark(bo.getRemark());
|
||||
add.setType(type);
|
||||
add.setDuration(duration);
|
||||
add.setSize(size);
|
||||
add.setCover(coverUrl);
|
||||
return baseMapper.insert(add) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据编辑业务对象更新设备语音
|
||||
*/
|
||||
@Override
|
||||
public Boolean updateByBo(AppDeviceVoiceBo bo) {
|
||||
AppDeviceVoice update = new AppDeviceVoice();
|
||||
update.setId(bo.getId());
|
||||
update.setVideoName(bo.getVideoName());
|
||||
update.setDeviceId(bo.getDeviceId());
|
||||
update.setRemark(bo.getRemark());
|
||||
return baseMapper.updateById(update) > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 校验并批量删除设备语音信息
|
||||
*/
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
// TODO: 可以在这里添加删除MinIO文件的逻辑
|
||||
return baseMapper.deleteBatchIds(ids) > 0;
|
||||
}
|
||||
|
||||
}
|
||||
@ -3,6 +3,12 @@
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.fuyuanshen.app.mapper.AppDeviceShareMapper">
|
||||
<delete id="deleteByDeviceIds">
|
||||
delete from app_device_share where device_id in
|
||||
<foreach item="item" collection="deviceIds" separator="," open="(" close=")">
|
||||
#{item}
|
||||
</foreach>
|
||||
</delete>
|
||||
|
||||
<select id="otherDeviceShareList" resultType="com.fuyuanshen.app.domain.vo.AppDeviceShareVo">
|
||||
select d.device_name,
|
||||
|
||||
@ -0,0 +1,57 @@
|
||||
<?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.AppDeviceVoiceMapper">
|
||||
|
||||
<resultMap type="com.fuyuanshen.app.domain.AppDeviceVoice" id="AppDeviceVoiceResult">
|
||||
<result property="id" column="id"/>
|
||||
<result property="videoName" column="video_name"/>
|
||||
<result property="videoUrl" column="video_url"/>
|
||||
<result property="deviceId" column="device_id"/>
|
||||
<result property="remark" column="remark"/>
|
||||
<result property="type" column="type"/>
|
||||
<result property="duration" column="duration"/>
|
||||
<result property="size" column="size"/>
|
||||
<result property="cover" column="cover"/>
|
||||
<result property="tenantId" column="tenant_id"/>
|
||||
<result property="createDept" column="create_dept"/>
|
||||
<result property="createBy" column="create_by"/>
|
||||
<result property="createTime" column="create_time"/>
|
||||
<result property="updateBy" column="update_by"/>
|
||||
<result property="updateTime" column="update_time"/>
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectAppDeviceVoiceVo">
|
||||
select id, video_name, video_url, device_id, remark, type, duration, size, cover, tenant_id, create_dept, create_by, create_time, update_by, update_time from app_device_voice
|
||||
</sql>
|
||||
|
||||
<select id="selectPage" parameterType="com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo" resultMap="AppDeviceVoiceResult">
|
||||
<include refid="selectAppDeviceVoiceVo"/>
|
||||
<where>
|
||||
<if test="videoName != null and videoName != ''"> and video_name like concat('%', #{videoName}, '%')</if>
|
||||
<if test="videoUrl != null and videoUrl != ''"> and video_url = #{videoUrl}</if>
|
||||
<if test="deviceId != null "> and device_id = #{deviceId}</if>
|
||||
<if test="type != null and type != ''"> and type = #{type}</if>
|
||||
<if test="duration != null "> and duration = #{duration}</if>
|
||||
<if test="size != null "> and size = #{size}</if>
|
||||
<if test="cover != null and cover != ''"> and cover = #{cover}</if>
|
||||
</where>
|
||||
order by create_time desc
|
||||
</select>
|
||||
|
||||
<select id="selectList" parameterType="com.fuyuanshen.app.domain.bo.AppDeviceVoiceBo" resultMap="AppDeviceVoiceResult">
|
||||
<include refid="selectAppDeviceVoiceVo"/>
|
||||
<where>
|
||||
<if test="videoName != null and videoName != ''"> and video_name like concat('%', #{videoName}, '%')</if>
|
||||
<if test="videoUrl != null and videoUrl != ''"> and video_url = #{videoUrl}</if>
|
||||
<if test="deviceId != null "> and device_id = #{deviceId}</if>
|
||||
<if test="type != null and type != ''"> and type = #{type}</if>
|
||||
<if test="duration != null "> and duration = #{duration}</if>
|
||||
<if test="size != null "> and size = #{size}</if>
|
||||
<if test="cover != null and cover != ''"> and cover = #{cover}</if>
|
||||
</where>
|
||||
order by create_time desc
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@ -3,9 +3,7 @@ package com.fuyuanshen.equipment.controller;
|
||||
|
||||
import com.alibaba.excel.EasyExcel;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fuyuanshen.common.core.constant.ResponseMessageConstants;
|
||||
import com.fuyuanshen.common.core.domain.R;
|
||||
import com.fuyuanshen.common.core.domain.ResponseVO;
|
||||
import com.fuyuanshen.common.core.domain.model.LoginUser;
|
||||
import com.fuyuanshen.common.core.utils.file.FileUtil;
|
||||
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
|
||||
@ -13,12 +11,13 @@ import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.common.web.core.BaseController;
|
||||
import com.fuyuanshen.customer.mapper.CustomerMapper;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceType;
|
||||
import com.fuyuanshen.equipment.domain.dto.DeviceExcelImportDTO;
|
||||
import com.fuyuanshen.equipment.domain.dto.ImportResult;
|
||||
import com.fuyuanshen.equipment.domain.form.DeviceForm;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
|
||||
import com.fuyuanshen.equipment.domain.vo.CustomerVo;
|
||||
import com.fuyuanshen.equipment.excel.DeviceImportParams;
|
||||
import com.fuyuanshen.equipment.excel.HeadValidateListener;
|
||||
import com.fuyuanshen.equipment.excel.UploadDeviceDataListener;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceMapper;
|
||||
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
|
||||
@ -39,7 +38,10 @@ import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @Description:
|
||||
@ -163,7 +165,7 @@ public class DeviceController extends BaseController {
|
||||
|
||||
|
||||
@Operation(summary = "导出数据设备")
|
||||
@GetMapping(value = "/download")
|
||||
@GetMapping(value = "/download1")
|
||||
public R<Void> exportDevice(HttpServletResponse response, DeviceQueryCriteria criteria) throws IOException {
|
||||
List<Device> devices = deviceService.queryAll(criteria);
|
||||
exportService.export(devices, response);
|
||||
@ -171,9 +173,36 @@ public class DeviceController extends BaseController {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 导出设备数据(包含完整设备类型信息)
|
||||
*
|
||||
* @param response HttpServletResponse对象
|
||||
* @param criteria 查询条件
|
||||
* @return R<Void>
|
||||
*/
|
||||
@Operation(summary = "导出设备数据(包含完整设备类型信息)")
|
||||
@GetMapping(value = "/download")
|
||||
public R<Void> exportDeviceWithFullTypeInfo(HttpServletResponse response, DeviceQueryCriteria criteria) {
|
||||
// 获取所有符合条件的设备
|
||||
List<Device> devices = deviceService.queryAll(criteria);
|
||||
// 获取所有设备类型信息
|
||||
List<DeviceType> deviceTypes = deviceTypeService.queryDeviceTypes();
|
||||
// 导出数据(包含完整设备类型信息)
|
||||
exportService.exportWithTypeInfo(devices, deviceTypes, response);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 导入设备数据
|
||||
*
|
||||
* @param file
|
||||
* @return
|
||||
* @throws BadRequestException
|
||||
*/
|
||||
@Operation(summary = "导入设备数据")
|
||||
@PostMapping(value = "/import", consumes = "multipart/form-data")
|
||||
public R<ImportResult> importData(@Parameter(name = "文件", required = true) @RequestPart("file") MultipartFile file) throws BadRequestException {
|
||||
@PostMapping(value = "/import1", consumes = "multipart/form-data")
|
||||
public R<ImportResult> importData1(@Parameter(name = "文件", required = true) @RequestPart("file") MultipartFile file) throws BadRequestException {
|
||||
|
||||
String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
|
||||
if (!("xlsx".equalsIgnoreCase(suffix))) {
|
||||
@ -207,6 +236,105 @@ public class DeviceController extends BaseController {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 导入设备数据
|
||||
*
|
||||
* @param file 文件
|
||||
* @return R<ImportResult>
|
||||
*/
|
||||
@Operation(summary = "导入设备数据")
|
||||
@PostMapping(value = "/import", consumes = "multipart/form-data")
|
||||
public R<ImportResult> importData(@Parameter(name = "文件", required = true) @RequestPart("file") MultipartFile file) throws BadRequestException {
|
||||
|
||||
String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
|
||||
if (!("xlsx".equalsIgnoreCase(suffix))) {
|
||||
throw new BadRequestException("只能上传Excel——xlsx格式文件");
|
||||
}
|
||||
|
||||
// 检查文件大小,限制为100MB
|
||||
if (file.getSize() > 100 * 10 * 1024 * 1024) {
|
||||
throw new BadRequestException("文件大小不能超过100MB");
|
||||
}
|
||||
|
||||
// 校验模板
|
||||
validateExcelTemplate(file);
|
||||
|
||||
ImportResult result = new ImportResult();
|
||||
try {
|
||||
LoginUser loginUser = LoginHelper.getLoginUser();
|
||||
DeviceImportParams params = DeviceImportParams.builder().ossService(ossService)
|
||||
.deviceService(deviceService).tenantId(loginUser.getTenantId())
|
||||
.file(file).filePath("").deviceMapper(deviceMapper).deviceTypeService(deviceTypeService)
|
||||
.deviceTypeMapper(deviceTypeMapper).userId(loginUser.getUserId())
|
||||
.build();
|
||||
// 创建监听器
|
||||
UploadDeviceDataListener listener = new UploadDeviceDataListener(params);
|
||||
// 读取Excel
|
||||
EasyExcel.read(file.getInputStream(), DeviceExcelImportDTO.class, listener).sheet().doRead();
|
||||
// 获取导入结果
|
||||
result = listener.getImportResult();
|
||||
// 设置响应消息
|
||||
String message = String.format("成功导入 %d 条数据,失败 %d 条", result.getSuccessCount(), result.getFailureCount());
|
||||
// 返回带有正确泛型的响应
|
||||
return R.ok(message, result);
|
||||
} catch (Exception e) {
|
||||
log.error("导入设备数据出错: {}", e.getMessage(), e);
|
||||
// 在异常情况下,设置默认结果
|
||||
String errorMessage = String.format("导入失败: %s。成功 %d 条,失败 %d 条", e.getMessage(), result.getSuccessCount(), result.getFailureCount());
|
||||
// 使用新方法确保类型正确
|
||||
return R.fail(errorMessage, result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 校验Excel模板是否正确
|
||||
*
|
||||
* @param file MultipartFile对象
|
||||
* @throws BadRequestException 当模板不正确时抛出异常
|
||||
*/
|
||||
private void validateExcelTemplate(MultipartFile file) throws BadRequestException {
|
||||
try {
|
||||
// 创建一个只读取表头的监听器
|
||||
HeadValidateListener headValidateListener = new HeadValidateListener();
|
||||
|
||||
// 使用EasyExcel读取表头
|
||||
EasyExcel.read(file.getInputStream(), headValidateListener)
|
||||
.sheet()
|
||||
.headRowNumber(0)
|
||||
.doRead();
|
||||
|
||||
// 获取读取到的表头信息
|
||||
List<String> actualHeaders = headValidateListener.getHeadNames();
|
||||
|
||||
// 定义必需的表头
|
||||
Set<String> requiredHeaders = new HashSet<>(Arrays.asList(
|
||||
"设备名称", "设备类型名称", "设备图片", "设备MAC", "蓝牙名称", "设备IMEI",
|
||||
"备注", "是否支持蓝牙", "定位方式", "通讯方式",
|
||||
"型号字典用于APP页面跳转", "型号字典用于PC页面跳转"
|
||||
));
|
||||
|
||||
// 检查必需的表头是否都存在
|
||||
Set<String> actualHeaderSet = new HashSet<>(actualHeaders);
|
||||
if (!actualHeaderSet.containsAll(requiredHeaders)) {
|
||||
requiredHeaders.removeAll(actualHeaderSet);
|
||||
throw new BadRequestException("Excel模板缺少必需的列: " + String.join(", ", requiredHeaders));
|
||||
}
|
||||
|
||||
// 检查第三列(索引为2)是否为"设备图片"
|
||||
if (actualHeaders.size() > 2 && !"设备图片".equals(actualHeaders.get(2))) {
|
||||
throw new BadRequestException("Excel模板不正确,第三列必须是'设备图片'列");
|
||||
}
|
||||
} catch (BadRequestException e) {
|
||||
throw e; // 直接重新抛出
|
||||
} catch (Exception e) {
|
||||
log.error("校验Excel模板时发生错误: {}", e.getMessage(), e);
|
||||
throw new BadRequestException("校验Excel模板时发生错误: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -4,6 +4,8 @@ import com.alibaba.excel.converters.Converter;
|
||||
import com.alibaba.excel.metadata.GlobalConfiguration;
|
||||
import com.alibaba.excel.metadata.data.WriteCellData;
|
||||
import com.alibaba.excel.metadata.property.ExcelContentProperty;
|
||||
import com.fuyuanshen.common.core.utils.file.ImageCompressUtil;
|
||||
import com.fuyuanshen.common.redis.utils.RedisUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@ -12,86 +14,256 @@ import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-06-0618:56
|
||||
*/
|
||||
|
||||
public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(IgnoreFailedImageConverter.class);
|
||||
|
||||
// 重试次数
|
||||
private static final int MAX_RETRIES = 3;
|
||||
// 指数退避初始延迟(毫秒)
|
||||
private static final int INITIAL_DELAY = 1000;
|
||||
// 图片压缩阈值(1MB)
|
||||
private static final int COMPRESSION_THRESHOLD = 1024 * 1024;
|
||||
// 压缩目标大小(100KB)
|
||||
private static final int COMPRESSION_TARGET = 100 * 1024;
|
||||
// 用于跟踪本次任务中使用到的URL缓存键
|
||||
private static final ThreadLocal<Set<String>> USED_CACHE_KEYS = new ThreadLocal<Set<String>>() {
|
||||
@Override
|
||||
protected Set<String> initialValue() {
|
||||
return new HashSet<>();
|
||||
}
|
||||
};
|
||||
|
||||
// 创建线程池用于并发处理图片
|
||||
private static final ExecutorService IMAGE_PROCESSING_EXECUTOR = Executors.newFixedThreadPool(
|
||||
Runtime.getRuntime().availableProcessors() * 2);
|
||||
|
||||
@Override
|
||||
public Class<?> supportJavaTypeKey() {
|
||||
return URL.class;
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public CellDataTypeEnum supportExcelTypeKey() {
|
||||
// return CellDataTypeEnum.STRING;
|
||||
// }
|
||||
|
||||
@Override
|
||||
public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
|
||||
if (value == null) {
|
||||
logger.debug("图片URL为空");
|
||||
logger.info("图片URL为空");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
try {
|
||||
logger.debug("开始加载图片: {}", value);
|
||||
URLConnection conn = value.openConnection();
|
||||
// 增加连接和读取超时时间
|
||||
conn.setConnectTimeout(10000); // 10秒连接超时
|
||||
conn.setReadTimeout(30000); // 30秒读取超时
|
||||
|
||||
// 添加User-Agent避免被服务器拦截
|
||||
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ExcelExporter/1.0");
|
||||
|
||||
// 如果是HTTP连接,设置一些额外的属性
|
||||
if (conn instanceof HttpURLConnection) {
|
||||
HttpURLConnection httpConn = (HttpURLConnection) conn;
|
||||
httpConn.setRequestMethod("GET");
|
||||
// 不使用缓存
|
||||
httpConn.setUseCaches(false);
|
||||
// 跟随重定向
|
||||
httpConn.setInstanceFollowRedirects(true);
|
||||
}
|
||||
|
||||
long contentLength = conn.getContentLengthLong();
|
||||
logger.debug("连接建立成功,图片大小: {} 字节", contentLength);
|
||||
|
||||
// 检查内容长度是否有效
|
||||
if (contentLength == 0) {
|
||||
logger.warn("图片文件为空: {}", value);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
// 限制图片大小(防止过大文件导致内存问题)
|
||||
if (contentLength > 10 * 1024 * 1024) { // 10MB限制
|
||||
logger.warn("图片文件过大 ({} bytes),跳过加载: {}", contentLength, value);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
try (InputStream inputStream = conn.getInputStream()) {
|
||||
// byte[] bytes = FileUtils.readInputStream(inputStream, value.toString());
|
||||
// 替代 FileUtils.readInputStream 的自定义方法
|
||||
byte[] bytes = readInputStream(inputStream);
|
||||
|
||||
// 检查读取到的数据是否为空
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
logger.warn("读取到空的图片数据: {}", value);
|
||||
// 使用CompletableFuture异步处理图片加载
|
||||
CompletableFuture<WriteCellData<?>> future = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return loadImageData(value);
|
||||
} catch (Exception e) {
|
||||
logger.error("异步加载图片失败: {}", value, e);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
logger.debug("成功读取图片数据,大小: {} 字节", bytes.length);
|
||||
return new WriteCellData<>(bytes);
|
||||
}
|
||||
}, IMAGE_PROCESSING_EXECUTOR);
|
||||
|
||||
// 设置超时时间,防止长时间阻塞
|
||||
return future.get(30, TimeUnit.SECONDS);
|
||||
} catch (Exception e) {
|
||||
// 静默忽略错误,只记录日志
|
||||
logger.warn("图片加载失败: {}, 原因: {}", value, e.getMessage(), e);
|
||||
// return null; // 返回null表示不写入图片
|
||||
return new WriteCellData<>(new byte[0]); // 返回空数组而不是 null
|
||||
logger.error("图片处理异常: {}", value, e);
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载图片数据的核心方法
|
||||
* @param value 图片URL
|
||||
* @return WriteCellData对象
|
||||
*/
|
||||
private WriteCellData<?> loadImageData(URL value) {
|
||||
String cacheKey = "excel:image:" + value.toString();
|
||||
|
||||
// 将当前使用的缓存键添加到集合中
|
||||
USED_CACHE_KEYS.get().add(cacheKey);
|
||||
|
||||
// 尝试从缓存获取
|
||||
String cachedData = RedisUtils.getCacheObject(cacheKey);
|
||||
if (cachedData != null) {
|
||||
// 从缓存中读取Base64编码的数据并解码
|
||||
byte[] cachedBytes = Base64.getDecoder().decode(cachedData);
|
||||
logger.info("从缓存获取图片数据: {}, 大小: {} 字节", value, cachedBytes.length);
|
||||
return new WriteCellData<>(cachedBytes);
|
||||
}
|
||||
|
||||
// 缓存未命中,从URL加载
|
||||
// 尝试多次加载图片
|
||||
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
logger.info("开始加载图片: {}, 尝试次数: {}", value, attempt);
|
||||
URLConnection conn = value.openConnection();
|
||||
// 增加连接和读取超时时间
|
||||
conn.setConnectTimeout(5000); // 5秒连接超时
|
||||
conn.setReadTimeout(15000); // 15秒读取超时
|
||||
|
||||
// 添加User-Agent避免被服务器拦截
|
||||
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 ExcelExporter/1.0");
|
||||
// 添加Connection: close避免保持连接
|
||||
conn.setRequestProperty("Connection", "close");
|
||||
|
||||
// 如果是HTTP连接,设置一些额外的属性
|
||||
if (conn instanceof HttpURLConnection) {
|
||||
HttpURLConnection httpConn = (HttpURLConnection) conn;
|
||||
httpConn.setRequestMethod("GET");
|
||||
// 不使用缓存
|
||||
httpConn.setUseCaches(false);
|
||||
// 跟随重定向
|
||||
httpConn.setInstanceFollowRedirects(true);
|
||||
|
||||
// 检查响应码
|
||||
int responseCode = httpConn.getResponseCode();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
logger.info("HTTP响应码异常: {}, URL: {}", responseCode, value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
// 等待后重试
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
long contentLength = conn.getContentLengthLong();
|
||||
logger.info("连接建立成功,图片大小: {} 字节", contentLength);
|
||||
|
||||
// 检查内容长度是否有效
|
||||
if (contentLength == 0) {
|
||||
logger.info("图片文件为空: {}", value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// 限制图片大小(防止过大文件导致内存问题)
|
||||
if (contentLength > 10 * 1024 * 1024) { // 10MB限制
|
||||
logger.info("图片文件过大 ({} bytes),跳过加载: {}", contentLength, value);
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
try (InputStream inputStream = conn.getInputStream()) {
|
||||
// byte[] bytes = FileUtils.readInputStream(inputStream, value.toString());
|
||||
// 替代 FileUtils.readInputStream 的自定义方法
|
||||
byte[] bytes = readInputStream(inputStream);
|
||||
|
||||
// 检查读取到的数据是否为空
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
logger.info("读取到空的图片数据: {}", value);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
waitForRetry(attempt);
|
||||
continue;
|
||||
} else {
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果图片大于1MB,则进行压缩
|
||||
if (bytes.length > COMPRESSION_THRESHOLD) {
|
||||
logger.info("图片大小超过1MB ({} bytes),开始压缩", bytes.length);
|
||||
long beforeCompressSize = bytes.length;
|
||||
|
||||
// 先尝试质量压缩
|
||||
byte[] compressed = ImageCompressUtil.compressImage(bytes, COMPRESSION_TARGET);
|
||||
|
||||
// 如果压缩后变大了,使用原始数据
|
||||
if (compressed.length >= bytes.length) {
|
||||
compressed = bytes;
|
||||
}
|
||||
|
||||
bytes = compressed;
|
||||
long afterCompressSize = bytes.length;
|
||||
logger.info("图片压缩完成,压缩前大小: {} bytes, 压缩后大小: {} bytes, 压缩率: {}",
|
||||
beforeCompressSize, afterCompressSize,
|
||||
String.format("%.2f", (1.0 - (double) afterCompressSize / beforeCompressSize) * 100));
|
||||
}
|
||||
|
||||
logger.info("成功读取图片数据,大小: {} 字节", bytes.length);
|
||||
// 将数据写入缓存,不设置过期时间,使用Base64编码存储
|
||||
String encodedData = Base64.getEncoder().encodeToString(bytes);
|
||||
RedisUtils.setCacheObject(cacheKey, encodedData);
|
||||
return new WriteCellData<>(bytes);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.info("图片加载失败: {}, 尝试次数: {}, 原因: {}", value, attempt, e.getMessage(), e);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
// 等待后重试
|
||||
waitForRetry(attempt);
|
||||
} else {
|
||||
// 最后一次尝试也失败了
|
||||
logger.info("图片加载最终失败,已重试 {} 次: {}", MAX_RETRIES, value, e);
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]); // 返回空数组而不是 null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有尝试都失败了
|
||||
// 将空数据写入缓存
|
||||
RedisUtils.setCacheObject(cacheKey, "");
|
||||
return new WriteCellData<>(new byte[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理未使用的缓存
|
||||
* 任务结束后调用此方法,删除本次任务中未使用的URL缓存
|
||||
*/
|
||||
public static void cleanUnusedCache() {
|
||||
Set<String> usedKeys = USED_CACHE_KEYS.get();
|
||||
if (usedKeys != null && !usedKeys.isEmpty()) {
|
||||
// 获取所有图片缓存键
|
||||
Iterable<String> allKeys = RedisUtils.keys("excel:image:*");
|
||||
if (allKeys != null) {
|
||||
// 删除未使用的缓存
|
||||
for (String key : allKeys) {
|
||||
if (!usedKeys.contains(key)) {
|
||||
RedisUtils.deleteObject(key);
|
||||
logger.info("删除未使用的缓存: {}", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 清理ThreadLocal
|
||||
USED_CACHE_KEYS.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待重试,使用指数退避策略
|
||||
*
|
||||
* @param attempt 当前尝试次数
|
||||
*/
|
||||
private void waitForRetry(int attempt) {
|
||||
try {
|
||||
long delay = (long) INITIAL_DELAY * (1L << (attempt - 1)); // 指数退避
|
||||
logger.info("等待 {} 毫秒后重试...", delay);
|
||||
Thread.sleep(delay);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@ -111,14 +283,48 @@ public class IgnoreFailedImageConverter implements Converter<URL> {
|
||||
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, bytesRead);
|
||||
totalBytes += bytesRead;
|
||||
|
||||
|
||||
// 如果读取的数据过大,提前终止
|
||||
if (totalBytes > 10 * 1024 * 1024) { // 10MB限制
|
||||
logger.warn("读取的图片数据超过10MB限制,提前终止");
|
||||
logger.info("读取的图片数据超过10MB限制,提前终止");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载图片到缓存
|
||||
* @param imageUrls 图片URL列表
|
||||
*/
|
||||
public static void preloadImages(Set<URL> imageUrls) {
|
||||
if (imageUrls == null || imageUrls.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("开始预加载 {} 张图片", imageUrls.size());
|
||||
|
||||
// 使用并行流并发预加载图片
|
||||
imageUrls.parallelStream().forEach(url -> {
|
||||
try {
|
||||
String cacheKey = "excel:image:" + url.toString();
|
||||
// 如果缓存中没有,则异步加载
|
||||
if (!RedisUtils.hasKey(cacheKey)) {
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
// 简化版图片加载逻辑,只加载到缓存
|
||||
new IgnoreFailedImageConverter().loadImageData(url);
|
||||
} catch (Exception e) {
|
||||
logger.warn("预加载图片失败: {}", url, e);
|
||||
}
|
||||
}, IMAGE_PROCESSING_EXECUTOR);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("预加载图片异常: {}", url, e);
|
||||
}
|
||||
});
|
||||
|
||||
logger.info("图片预加载任务已提交");
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,7 +60,7 @@ public class DeviceType extends TenantEntity {
|
||||
private String networkWay;
|
||||
|
||||
@Schema(title = "通讯方式", example = "通讯方式 0:4G;1:蓝牙,2 4G&蓝牙")
|
||||
private Integer communicationMode;
|
||||
private String communicationMode;
|
||||
|
||||
/**
|
||||
* 创建人名称
|
||||
|
||||
@ -12,6 +12,7 @@ import lombok.EqualsAndHashCode;
|
||||
*/
|
||||
@Data
|
||||
public class AppDeviceBo {
|
||||
|
||||
/**
|
||||
* 设备IMEI
|
||||
*/
|
||||
@ -25,10 +26,11 @@ public class AppDeviceBo {
|
||||
/**
|
||||
* 通讯方式 0:4G;1:蓝牙,2 4G&蓝牙
|
||||
*/
|
||||
@NotNull(message = "通讯方式不能为空", groups = { EditGroup.class })
|
||||
@NotNull(message = "通讯方式不能为空", groups = {EditGroup.class})
|
||||
private Integer communicationMode;
|
||||
|
||||
private String sendMsg;
|
||||
|
||||
private Long deviceId;
|
||||
|
||||
}
|
||||
|
||||
@ -1,24 +1,21 @@
|
||||
package com.fuyuanshen.equipment.domain.dto;
|
||||
|
||||
import com.alibaba.excel.annotation.ExcelIgnore;
|
||||
import com.alibaba.excel.annotation.ExcelProperty;
|
||||
import com.alibaba.excel.annotation.write.style.ColumnWidth;
|
||||
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
|
||||
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
|
||||
import com.alibaba.excel.converters.bytearray.ByteArrayImageConverter;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-06-0710:00
|
||||
* @date: 2025-06-07 10:00
|
||||
*/
|
||||
@Data
|
||||
@HeadRowHeight(20) // 表头行高
|
||||
@ContentRowHeight(100) // 内容行高
|
||||
public class DeviceExcelImportDTO {
|
||||
|
||||
// @ExcelProperty("设备类型")
|
||||
// private Long deviceType;
|
||||
|
||||
@ExcelProperty("设备名称")
|
||||
@ColumnWidth(20)
|
||||
private String deviceName;
|
||||
@ -26,14 +23,23 @@ public class DeviceExcelImportDTO {
|
||||
@ExcelProperty("设备类型名称")
|
||||
private String typeName;
|
||||
|
||||
// @ExcelProperty(value = "设备图片", converter = ByteArrayImageConverter.class)
|
||||
// @ColumnWidth(15)
|
||||
// private byte[] devicePic;
|
||||
//
|
||||
// // 添加图片写入方法
|
||||
// public void setDevicePicFromBytes(byte[] bytes) {
|
||||
// this.devicePic = bytes;
|
||||
// }
|
||||
/**
|
||||
* 设备图片
|
||||
* 导入时的图片处理方式:
|
||||
* 在导入过程中,图片不是通过Excel单元格中的文本数据(如URL)来处理的
|
||||
* 而是直接从Excel文件中提取嵌入的图片数据
|
||||
* 代码通过POI库直接读取Excel中的图片对象,然后上传到OSS并生成URL
|
||||
*/
|
||||
@ExcelProperty("设备图片")
|
||||
@ColumnWidth(20)
|
||||
private byte[] devicePic;
|
||||
|
||||
/**
|
||||
* 用于存储实际图片数据的字段
|
||||
* 使用@ExcelIgnore注解忽略该字段,避免创建额外的列
|
||||
*/
|
||||
@ExcelIgnore
|
||||
private byte[] imageData;
|
||||
|
||||
@ExcelProperty("设备MAC")
|
||||
@ColumnWidth(20)
|
||||
@ -46,18 +52,46 @@ public class DeviceExcelImportDTO {
|
||||
@ExcelProperty("蓝牙名称")
|
||||
private String bluetoothName;
|
||||
|
||||
// @ExcelProperty("设备SN")
|
||||
// @ColumnWidth(20)
|
||||
// private String deviceSn;
|
||||
//
|
||||
// @ExcelProperty("经度")
|
||||
// private String longitude;
|
||||
//
|
||||
// @ExcelProperty("纬度")
|
||||
// private String latitude;
|
||||
|
||||
@ExcelProperty("备注")
|
||||
@ColumnWidth(30)
|
||||
private String remark;
|
||||
|
||||
/*
|
||||
*设备类型数据
|
||||
*/
|
||||
@ExcelProperty("是否支持蓝牙")
|
||||
@ColumnWidth(15)
|
||||
private String isSupportBle;
|
||||
|
||||
@ExcelProperty("定位方式")
|
||||
@ColumnWidth(20)
|
||||
private String locateMode;
|
||||
|
||||
@ExcelProperty("通讯方式")
|
||||
@ColumnWidth(20)
|
||||
private String communicationMode;
|
||||
|
||||
/**
|
||||
* 型号字典用于APP页面跳转
|
||||
* app_model_dictionary
|
||||
*/
|
||||
@ExcelProperty("型号字典用于APP页面跳转")
|
||||
@ColumnWidth(20)
|
||||
private String appModelDictionary;
|
||||
|
||||
/**
|
||||
* 型号字典用于PC页面跳转
|
||||
* pc_model_dictionary
|
||||
*/
|
||||
@ExcelProperty("型号字典用于PC页面跳转")
|
||||
@ColumnWidth(20)
|
||||
private String pcModelDictionary;
|
||||
|
||||
/**
|
||||
* 错误原因
|
||||
*/
|
||||
@ExcelProperty("错误原因")
|
||||
@ColumnWidth(30)
|
||||
private String errorMessage;
|
||||
|
||||
}
|
||||
@ -0,0 +1,100 @@
|
||||
package com.fuyuanshen.equipment.domain.dto;
|
||||
|
||||
import com.alibaba.excel.annotation.ExcelProperty;
|
||||
import com.alibaba.excel.annotation.write.style.ColumnWidth;
|
||||
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
|
||||
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
|
||||
import com.fuyuanshen.equipment.converter.IgnoreFailedImageConverter;
|
||||
import lombok.Data;
|
||||
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* 设备及完整类型信息导出DTO
|
||||
*
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-11-04 16:25
|
||||
*/
|
||||
@Data
|
||||
@HeadRowHeight(20) // 表头行高
|
||||
@ContentRowHeight(100) // 内容行高
|
||||
public class DeviceWithTypeExcelExportDTO {
|
||||
|
||||
@ExcelProperty("设备名称")
|
||||
@ColumnWidth(20)
|
||||
private String deviceName;
|
||||
|
||||
@ExcelProperty("设备类型名称")
|
||||
@ColumnWidth(20)
|
||||
private String typeName;
|
||||
|
||||
@ExcelProperty(value = "设备图片", converter = IgnoreFailedImageConverter.class)
|
||||
// @ExcelProperty(value = "设备图片")
|
||||
@ColumnWidth(30) // 设置图片列宽度
|
||||
private URL devicePic; // 使用URL类型
|
||||
|
||||
@ExcelProperty("设备MAC")
|
||||
@ColumnWidth(20)
|
||||
private String deviceMac;
|
||||
|
||||
@ExcelProperty("蓝牙名称")
|
||||
@ColumnWidth(20)
|
||||
private String bluetoothName;
|
||||
|
||||
@ExcelProperty("设备IMEI")
|
||||
@ColumnWidth(20)
|
||||
private String deviceImei;
|
||||
|
||||
@ExcelProperty("备注")
|
||||
@ColumnWidth(30)
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 绑定状态
|
||||
* 0 未绑定
|
||||
* 1 已绑定
|
||||
*/
|
||||
@ExcelProperty("绑定状态")
|
||||
@ColumnWidth(20)
|
||||
private String bindingStatus;
|
||||
|
||||
@ExcelProperty("创建时间")
|
||||
@ColumnWidth(20)
|
||||
private String createTime;
|
||||
|
||||
@ExcelProperty("创建人")
|
||||
@ColumnWidth(20)
|
||||
private String createBy;
|
||||
|
||||
/*
|
||||
*设备类型数据
|
||||
*/
|
||||
@ExcelProperty("是否支持蓝牙")
|
||||
@ColumnWidth(15)
|
||||
private String isSupportBle;
|
||||
|
||||
@ExcelProperty("定位方式")
|
||||
@ColumnWidth(20)
|
||||
private String locateMode;
|
||||
|
||||
@ExcelProperty("通讯方式")
|
||||
@ColumnWidth(20)
|
||||
private String communicationMode;
|
||||
|
||||
/**
|
||||
* 型号字典用于APP页面跳转
|
||||
* app_model_dictionary
|
||||
*/
|
||||
@ExcelProperty("型号字典用于APP页面跳转")
|
||||
@ColumnWidth(20)
|
||||
private String appModelDictionary;
|
||||
|
||||
/**
|
||||
* 型号字典用于PC页面跳转
|
||||
* pc_model_dictionary
|
||||
*/
|
||||
@ExcelProperty("型号字典用于PC页面跳转")
|
||||
@ColumnWidth(20)
|
||||
private String pcModelDictionary;
|
||||
|
||||
}
|
||||
@ -26,8 +26,6 @@ public class DeviceForm {
|
||||
@Schema(title = "客户号")
|
||||
private Long customerId;
|
||||
|
||||
/*@Schema(value = "设备编号")
|
||||
private String deviceNo;*/
|
||||
|
||||
@NotBlank(message = "设备名称不能为空")
|
||||
@Schema(title = "设备名称", required = true)
|
||||
@ -56,4 +54,25 @@ public class DeviceForm {
|
||||
@Schema(title = "备注")
|
||||
private String remark;
|
||||
|
||||
|
||||
// 设备类型相关字段
|
||||
@Schema(title = "设备类型名称")
|
||||
private String typeName;
|
||||
|
||||
@Schema(title = "是否支持蓝牙")
|
||||
private String isSupportBle;
|
||||
|
||||
@Schema(title = "定位方式")
|
||||
private String locateMode;
|
||||
|
||||
@Schema(title = "通讯方式")
|
||||
private String communicationMode;
|
||||
|
||||
@Schema(title = "APP模型字典")
|
||||
private String appModelDictionary;
|
||||
|
||||
@Schema(title = "PC模型字典")
|
||||
private String pcModelDictionary;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -86,4 +86,5 @@ public class AppDeviceVo implements Serializable {
|
||||
* 设备详情页面
|
||||
*/
|
||||
private String detailPageUrl;
|
||||
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@ package com.fuyuanshen.equipment.domain.vo;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 数据总览
|
||||
* 首页数据总览
|
||||
*
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-09-0114:24
|
||||
|
||||
@ -58,7 +58,6 @@ public class WebDeviceVo implements Serializable {
|
||||
*/
|
||||
private Integer deviceStatus;
|
||||
|
||||
|
||||
/**绑定状态
|
||||
* 0 未绑定
|
||||
* 1 已绑定
|
||||
|
||||
@ -0,0 +1,54 @@
|
||||
package com.fuyuanshen.equipment.excel;
|
||||
|
||||
import com.alibaba.excel.context.AnalysisContext;
|
||||
import com.alibaba.excel.event.AnalysisEventListener;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 读取表头 监听器
|
||||
*
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-11-1809:36
|
||||
*/
|
||||
@Slf4j
|
||||
public class HeadValidateListener extends AnalysisEventListener<Map<Integer, String>> {
|
||||
|
||||
private List<String> headNames = new ArrayList<>();
|
||||
|
||||
|
||||
/**
|
||||
* When analysis one row trigger invoke function.
|
||||
*
|
||||
* @param headMap one row value. It is same as {@link AnalysisContext#readRowHolder()}
|
||||
* @param context analysis context
|
||||
*/
|
||||
@Override
|
||||
public void invoke(Map<Integer, String> headMap, AnalysisContext context) {
|
||||
log.info("解析到一条数据: {}", JSON.toJSONString(headMap));
|
||||
// 按顺序收集表头名称
|
||||
for (int i = 0; i < headMap.size(); i++) {
|
||||
headNames.add(headMap.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* if have something to do after all analysis
|
||||
*
|
||||
* @param context
|
||||
*/
|
||||
@Override
|
||||
public void doAfterAllAnalysed(AnalysisContext context) {
|
||||
// 读取完成后不需要额外操作
|
||||
}
|
||||
|
||||
|
||||
public List<String> getHeadNames() {
|
||||
return headNames;
|
||||
}
|
||||
|
||||
}
|
||||
@ -5,8 +5,7 @@ import com.alibaba.excel.EasyExcel;
|
||||
import com.alibaba.excel.context.AnalysisContext;
|
||||
import com.alibaba.excel.read.listener.ReadListener;
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.fuyuanshen.common.core.domain.model.LoginUser;
|
||||
import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.common.core.utils.file.ImageCompressUtil;
|
||||
import com.fuyuanshen.equipment.constants.DeviceConstants;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceType;
|
||||
@ -46,38 +45,41 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
}
|
||||
|
||||
|
||||
public ImportResult getImportResult() {
|
||||
public ImportResult getImportResult1() {
|
||||
ImportResult result = new ImportResult();
|
||||
result.setSuccessCount(successCount);
|
||||
result.setFailureCount(failureCount);
|
||||
|
||||
// 准备失败记录(包含图片数据)
|
||||
// 准备失败记录
|
||||
List<DeviceExcelImportDTO> failedRecordsWithImages = new ArrayList<>();
|
||||
|
||||
for (DeviceExcelImportDTO failedRecord : failedRecords) {
|
||||
// 创建一个映射,用于存储失败记录行号与图片数据的关系
|
||||
Map<Integer, byte[]> errorReportImageMap = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < failedRecords.size(); i++) {
|
||||
DeviceExcelImportDTO failedRecord = failedRecords.get(i);
|
||||
// 创建副本,避免修改原始数据
|
||||
DeviceExcelImportDTO recordWithImage = new DeviceExcelImportDTO();
|
||||
BeanUtil.copyProperties(failedRecord, recordWithImage);
|
||||
// 设置图片占位符,让用户知道这里有图片
|
||||
// recordWithImage.setDevicePic("[图片]");
|
||||
failedRecordsWithImages.add(recordWithImage);
|
||||
|
||||
// 获取原始行号
|
||||
Integer rowIndex = null;
|
||||
Integer originalRowIndex = null;
|
||||
for (Map.Entry<Integer, DeviceExcelImportDTO> entry : rowDtoMap.entrySet()) {
|
||||
if (entry.getValue() == failedRecord) {
|
||||
rowIndex = entry.getKey();
|
||||
originalRowIndex = entry.getKey();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (rowIndex != null) {
|
||||
// 创建副本,避免修改原始数据
|
||||
DeviceExcelImportDTO recordWithImage = new DeviceExcelImportDTO();
|
||||
BeanUtil.copyProperties(failedRecord, recordWithImage);
|
||||
|
||||
// 设置图片数据
|
||||
byte[] imageData = rowImageMap.get(rowIndex);
|
||||
// 保存图片数据用于错误报告
|
||||
if (originalRowIndex != null) {
|
||||
byte[] imageData = rowImageMap.get(originalRowIndex);
|
||||
if (imageData != null) {
|
||||
// recordWithImage.setDevicePicFromBytes(imageData);
|
||||
errorReportImageMap.put(i, imageData); // 使用新的列表索引
|
||||
}
|
||||
|
||||
failedRecordsWithImages.add(recordWithImage);
|
||||
} else {
|
||||
failedRecordsWithImages.add(failedRecord);
|
||||
}
|
||||
}
|
||||
|
||||
@ -99,7 +101,8 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
|
||||
// 保存错误报告到文件(包含图片)
|
||||
File errorFile = new File(errorDir, fileName);
|
||||
EasyExcel.write(errorFile, DeviceExcelImportDTO.class).registerWriteHandler(new ImageWriteHandler()) // 添加图片处理
|
||||
EasyExcel.write(errorFile, DeviceExcelImportDTO.class)
|
||||
.registerWriteHandler(new ImageWriteHandler(errorReportImageMap)) // 传递图片数据映射
|
||||
.sheet("失败数据").doWrite(failedRecordsWithImages);
|
||||
|
||||
// 生成访问URL
|
||||
@ -114,6 +117,79 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
return result;
|
||||
}
|
||||
|
||||
public ImportResult getImportResult() {
|
||||
ImportResult result = new ImportResult();
|
||||
result.setSuccessCount(successCount);
|
||||
result.setFailureCount(failureCount);
|
||||
|
||||
// 准备失败记录
|
||||
List<DeviceExcelImportDTO> failedRecordsWithImages = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < failedRecords.size(); i++) {
|
||||
DeviceExcelImportDTO failedRecord = failedRecords.get(i);
|
||||
// 创建副本,避免修改原始数据
|
||||
DeviceExcelImportDTO recordWithImage = new DeviceExcelImportDTO();
|
||||
BeanUtil.copyProperties(failedRecord, recordWithImage);
|
||||
|
||||
// 获取原始行号
|
||||
Integer originalRowIndex = null;
|
||||
for (Map.Entry<Integer, DeviceExcelImportDTO> entry : rowDtoMap.entrySet()) {
|
||||
if (entry.getValue() == failedRecord) {
|
||||
originalRowIndex = entry.getKey();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 保存图片数据用于错误报告
|
||||
if (originalRowIndex != null) {
|
||||
byte[] imageData = rowImageMap.get(originalRowIndex);
|
||||
if (imageData != null) {
|
||||
// recordWithImage.setImageData(imageData);
|
||||
recordWithImage.setDevicePic(imageData);
|
||||
}
|
||||
}
|
||||
|
||||
failedRecordsWithImages.add(recordWithImage);
|
||||
}
|
||||
|
||||
result.setFailedRecords(failedRecordsWithImages);
|
||||
|
||||
// 生成错误报告
|
||||
if (!failedRecordsWithImages.isEmpty()) {
|
||||
try {
|
||||
// 生成唯一的文件名
|
||||
String fileName = "import_errors_" + System.currentTimeMillis() + ".xlsx";
|
||||
|
||||
// 创建错误报告目录
|
||||
String errorDirPath = params.getFilePath() + DeviceConstants.ERROR_REPORT_DIR;
|
||||
File errorDir = new File(errorDirPath);
|
||||
if (!errorDir.exists() && !errorDir.mkdirs()) {
|
||||
log.error("无法创建错误报告目录: {}", errorDirPath);
|
||||
return result;
|
||||
}
|
||||
|
||||
// 保存错误报告到文件(包含图片)
|
||||
File errorFile = new File(errorDir, fileName);
|
||||
EasyExcel.write(errorFile, DeviceExcelImportDTO.class)
|
||||
.sheet("失败数据").doWrite(failedRecordsWithImages);
|
||||
|
||||
// 生成访问URL
|
||||
SysOssVo upload = params.getOssService().upload(errorFile);
|
||||
String url = upload.getUrl();
|
||||
// 将http://替换为https://,但不影响已经是https://的URL
|
||||
if (url.startsWith("http://")) {
|
||||
url = "https://" + url.substring(7);
|
||||
}
|
||||
result.setErrorExcelUrl(url);
|
||||
log.info("错误报告已保存: {}", errorFile.getAbsolutePath());
|
||||
log.info("错误报告已保存: {}", url);
|
||||
} catch (Exception e) {
|
||||
log.error("生成错误报告失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(DeviceExcelImportDTO data, AnalysisContext context) {
|
||||
@ -142,14 +218,232 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
|
||||
|
||||
private void processDataRowByRow() {
|
||||
LoginUser loginUser = LoginHelper.getLoginUser();
|
||||
// 如果没有数据,直接返回
|
||||
if (rowIndexList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 批量处理设备类型,减少数据库查询次数
|
||||
Set<String> typeNames = new HashSet<>();
|
||||
for (Integer rowIndex : rowIndexList) {
|
||||
Device device = rowDeviceMap.get(rowIndex);
|
||||
if (device != null && device.getTypeName() != null) {
|
||||
typeNames.add(device.getTypeName());
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询所有设备类型
|
||||
Map<String, DeviceType> deviceTypeMap = new HashMap<>();
|
||||
if (!typeNames.isEmpty()) {
|
||||
List<DeviceType> deviceTypes = params.getDeviceTypeService().queryByNames(new ArrayList<>(typeNames));
|
||||
for (DeviceType deviceType : deviceTypes) {
|
||||
deviceTypeMap.put(deviceType.getTypeName(), deviceType);
|
||||
}
|
||||
}
|
||||
|
||||
for (Integer rowIndex : rowIndexList) {
|
||||
Device device = rowDeviceMap.get(rowIndex);
|
||||
DeviceExcelImportDTO originalDto = rowDtoMap.get(rowIndex);
|
||||
try {
|
||||
// 从缓存中获取设备类型
|
||||
DeviceType deviceType = deviceTypeMap.get(device.getTypeName());
|
||||
|
||||
DeviceForm deviceForm = new DeviceForm();
|
||||
deviceForm.setDeviceName(device.getDeviceName());
|
||||
deviceForm.setDeviceType(deviceType != null ? deviceType.getId() : null);
|
||||
deviceForm.setTypeName(device.getTypeName());
|
||||
deviceForm.setRemark(device.getRemark());
|
||||
deviceForm.setDeviceMac(device.getDeviceMac());
|
||||
deviceForm.setDeviceImei(device.getDeviceImei());
|
||||
deviceForm.setBluetoothName(device.getBluetoothName());
|
||||
deviceForm.setDevicePic(device.getDevicePic());
|
||||
|
||||
// 设置设备类型相关信息,供设备服务内部创建设备类型时使用
|
||||
if (deviceType == null) {
|
||||
deviceForm.setIsSupportBle(originalDto.getIsSupportBle());
|
||||
deviceForm.setLocateMode(originalDto.getLocateMode());
|
||||
deviceForm.setCommunicationMode(originalDto.getCommunicationMode());
|
||||
deviceForm.setAppModelDictionary(originalDto.getAppModelDictionary());
|
||||
deviceForm.setPcModelDictionary(originalDto.getPcModelDictionary());
|
||||
}
|
||||
|
||||
params.getDeviceService().addDevice(deviceForm);
|
||||
successCount++;
|
||||
log.info("行 {} 数据插入成功", rowIndex);
|
||||
} catch (Exception e) {
|
||||
failureCount++;
|
||||
originalDto.setErrorMessage(e.getMessage());
|
||||
// originalDto.setErrorMessage("数据有误,请核对模板后,确认数据无误后,重新再试!!!");
|
||||
failedRecords.add(originalDto);
|
||||
log.error("行 {} 数据插入失败: {}", rowIndex, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理图片数据
|
||||
*/
|
||||
private void processImages() {
|
||||
// 如果没有数据行,直接返回
|
||||
if (rowIndexList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否有图片需要处理
|
||||
try {
|
||||
// 只在确实有图片时才打开文件处理
|
||||
boolean hasImages = false;
|
||||
try (OPCPackage opcPackage = OPCPackage.open(params.getFile().getInputStream())) {
|
||||
ZipSecureFile.setMinInflateRatio(-1.0d);
|
||||
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
|
||||
XSSFSheet sheet = workbook.getSheetAt(0);
|
||||
|
||||
XSSFDrawing drawing = sheet.getDrawingPatriarch();
|
||||
if (drawing != null) {
|
||||
for (XSSFShape shape : drawing.getShapes()) {
|
||||
if (shape instanceof XSSFPicture) {
|
||||
hasImages = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("检查图片时发生异常: {}", e.getMessage());
|
||||
// 如果检查图片失败,继续处理数据
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果没有图片,直接返回
|
||||
if (!hasImages) {
|
||||
log.info("未检测到图片,跳过图片处理");
|
||||
return;
|
||||
}
|
||||
|
||||
// 有图片时才进行处理
|
||||
try (OPCPackage opcPackage = OPCPackage.open(params.getFile().getInputStream())) {
|
||||
ZipSecureFile.setMinInflateRatio(-1.0d);
|
||||
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
|
||||
XSSFSheet sheet = workbook.getSheetAt(0);
|
||||
|
||||
XSSFDrawing drawing = sheet.getDrawingPatriarch();
|
||||
if (drawing == null) return;
|
||||
|
||||
for (XSSFShape shape : drawing.getShapes()) {
|
||||
if (shape instanceof XSSFPicture) {
|
||||
XSSFPicture picture = (XSSFPicture) shape;
|
||||
XSSFClientAnchor anchor = picture.getPreferredSize();
|
||||
int rowIndex = anchor.getRow1();
|
||||
int colIndex = anchor.getCol1();
|
||||
|
||||
if (colIndex == 2) {
|
||||
Device device = rowDeviceMap.get(rowIndex);
|
||||
if (device != null) {
|
||||
try {
|
||||
byte[] imageData = picture.getPictureData().getData();
|
||||
|
||||
// 检查图片大小,如果超过5MB则拒绝上传
|
||||
if (imageData.length > 5 * 1024 * 1024) {
|
||||
String errorMsg = "图片大小超过5MB限制,请压缩后重新上传";
|
||||
log.warn("行 {} 图片过大: {} bytes", rowIndex, imageData.length);
|
||||
// 将错误信息添加到该行的DTO中
|
||||
DeviceExcelImportDTO dto = rowDtoMap.get(rowIndex);
|
||||
if (dto != null) {
|
||||
dto.setErrorMessage(errorMsg);
|
||||
failedRecords.add(dto);
|
||||
failureCount++;
|
||||
}
|
||||
device.setDevicePic(null); // 设置为空,让插入继续
|
||||
continue; // 跳过当前图片处理
|
||||
}
|
||||
|
||||
// 表示Excel表格中的第3列(因为索引从0开始计算)
|
||||
String extraValue = getCellValue(sheet, rowIndex, 2);
|
||||
String imageUrl = uploadAndGenerateUrl(imageData, extraValue);
|
||||
device.setDevicePic(imageUrl);
|
||||
|
||||
// 2. 保存图片数据到DTO,用于错误报告
|
||||
rowImageMap.put(rowIndex, imageData);
|
||||
} catch (Exception e) {
|
||||
log.error("行 {} 图片处理失败: {}", rowIndex, e.getMessage());
|
||||
device.setDevicePic(null); // 设置为空,让插入继续
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("图片处理失败:{}", e.getMessage(), e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("图片处理过程中发生异常: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void processDataRowByRow1() {
|
||||
for (Integer rowIndex : rowIndexList) {
|
||||
Device device = rowDeviceMap.get(rowIndex);
|
||||
DeviceExcelImportDTO originalDto = rowDtoMap.get(rowIndex);
|
||||
try {
|
||||
// 设备类型
|
||||
DeviceType deviceType = params.getDeviceTypeService().queryByName(device.getTypeName());
|
||||
// params.getDeviceService().save(device);
|
||||
|
||||
// 如果设备类型不存在,则创建新的设备类型
|
||||
if (deviceType == null) {
|
||||
DeviceType newDeviceType = new DeviceType();
|
||||
newDeviceType.setTypeName(device.getTypeName());
|
||||
newDeviceType.setIsSupportBle("是".equals(originalDto.getIsSupportBle()) || "1".equals(originalDto.getIsSupportBle()));
|
||||
|
||||
// 设置定位方式
|
||||
if (originalDto.getLocateMode() != null) {
|
||||
switch (originalDto.getLocateMode()) {
|
||||
case "无":
|
||||
newDeviceType.setLocateMode("0");
|
||||
break;
|
||||
case "GPS":
|
||||
newDeviceType.setLocateMode("1");
|
||||
break;
|
||||
case "基站":
|
||||
newDeviceType.setLocateMode("2");
|
||||
break;
|
||||
case "wifi":
|
||||
newDeviceType.setLocateMode("3");
|
||||
break;
|
||||
case "北斗":
|
||||
newDeviceType.setLocateMode("4");
|
||||
break;
|
||||
default:
|
||||
newDeviceType.setLocateMode(originalDto.getLocateMode());
|
||||
}
|
||||
}
|
||||
|
||||
// 设置通讯方式
|
||||
if (originalDto.getCommunicationMode() != null) {
|
||||
switch (originalDto.getCommunicationMode()) {
|
||||
case "4G":
|
||||
newDeviceType.setCommunicationMode("0");
|
||||
break;
|
||||
case "蓝牙":
|
||||
newDeviceType.setCommunicationMode("1");
|
||||
break;
|
||||
case "4G&蓝牙":
|
||||
newDeviceType.setCommunicationMode("2");
|
||||
break;
|
||||
default:
|
||||
newDeviceType.setCommunicationMode(originalDto.getCommunicationMode());
|
||||
}
|
||||
}
|
||||
|
||||
newDeviceType.setAppModelDictionary(originalDto.getAppModelDictionary());
|
||||
newDeviceType.setPcModelDictionary(originalDto.getPcModelDictionary());
|
||||
|
||||
// 创建新的设备类型
|
||||
params.getDeviceTypeService().create(newDeviceType);
|
||||
|
||||
// 重新查询确保获取到正确的ID
|
||||
deviceType = params.getDeviceTypeService().queryByName(device.getTypeName());
|
||||
}
|
||||
|
||||
DeviceForm deviceForm = new DeviceForm();
|
||||
deviceForm.setDeviceName(device.getDeviceName());
|
||||
deviceForm.setDeviceType(deviceType.getId());
|
||||
@ -163,13 +457,19 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
log.info("行 {} 数据插入成功", rowIndex);
|
||||
} catch (Exception e) {
|
||||
failureCount++;
|
||||
originalDto.setErrorMessage(e.getMessage());
|
||||
// originalDto.setErrorMessage("数据有误,请核对模板后,确认数据无误后,重新再试!!!");
|
||||
failedRecords.add(originalDto);
|
||||
log.error("行 {} 数据插入失败: {}", rowIndex, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processImages() {
|
||||
|
||||
/**
|
||||
* 处理图片数据
|
||||
*/
|
||||
private void processImages1() {
|
||||
try (OPCPackage opcPackage = OPCPackage.open(params.getFile().getInputStream())) {
|
||||
ZipSecureFile.setMinInflateRatio(-1.0d);
|
||||
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
|
||||
@ -190,6 +490,22 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
if (device != null) {
|
||||
try {
|
||||
byte[] imageData = picture.getPictureData().getData();
|
||||
|
||||
// 检查图片大小,如果超过5MB则拒绝上传
|
||||
if (imageData.length > 5 * 1024 * 1024) {
|
||||
String errorMsg = "图片大小超过5MB限制,请压缩后重新上传";
|
||||
log.warn("行 {} 图片过大: {} bytes", rowIndex, imageData.length);
|
||||
// 将错误信息添加到该行的DTO中
|
||||
DeviceExcelImportDTO dto = rowDtoMap.get(rowIndex);
|
||||
if (dto != null) {
|
||||
dto.setErrorMessage(errorMsg);
|
||||
failedRecords.add(dto);
|
||||
failureCount++;
|
||||
}
|
||||
device.setDevicePic(null); // 设置为空,让插入继续
|
||||
continue; // 跳过当前图片处理
|
||||
}
|
||||
|
||||
// 表示Excel表格中的第3列(因为索引从0开始计算)
|
||||
String extraValue = getCellValue(sheet, rowIndex, 2);
|
||||
String imageUrl = uploadAndGenerateUrl(imageData, extraValue);
|
||||
@ -224,9 +540,16 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// 如果图片超过500KB,则进行压缩优化
|
||||
if (imageData.length > 500 * 1024) {
|
||||
log.info("检测到大图片 ({} bytes),正在进行压缩优化...", imageData.length);
|
||||
imageData = ImageCompressUtil.compressImage(imageData, 500 * 1024); // 压缩到500KB以下
|
||||
}
|
||||
|
||||
String fileExtension = "jpg";
|
||||
String newFileName = "PS_" + new Random(8) + "." + fileExtension;
|
||||
SysOssVo upload = params.getOssService().upload(imageData, newFileName);
|
||||
log.info("图片保存成功,URL: {}", upload.getUrl());
|
||||
return upload.getUrl();
|
||||
} catch (Exception e) {
|
||||
log.error("保存图片失败", e);
|
||||
@ -234,4 +557,5 @@ public class UploadDeviceDataListener implements ReadListener<DeviceExcelImportD
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -4,66 +4,95 @@ import com.alibaba.excel.write.handler.SheetWriteHandler;
|
||||
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
|
||||
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFDrawing;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author: 默苍璃
|
||||
* @date: 2025-06-0718:05
|
||||
* @date: 2025-06-07 18:05
|
||||
*/
|
||||
public class ImageWriteHandler implements SheetWriteHandler {
|
||||
|
||||
private Map<Integer, byte[]> imageMap;
|
||||
private int imageColIndex;
|
||||
|
||||
public ImageWriteHandler(Map<Integer, byte[]> imageMap) {
|
||||
this(imageMap, 2);
|
||||
}
|
||||
|
||||
public ImageWriteHandler(Map<Integer, byte[]> imageMap, int imageColIndex) {
|
||||
this.imageMap = imageMap;
|
||||
this.imageColIndex = imageColIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
|
||||
if (imageMap == null || imageMap.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Workbook workbook = writeWorkbookHolder.getWorkbook();
|
||||
Sheet sheet = writeSheetHolder.getSheet();
|
||||
|
||||
// 设置图片列的宽度
|
||||
sheet.setColumnWidth(imageColIndex, 20 * 256); // 20个字符宽度
|
||||
|
||||
for (Map.Entry<Integer, byte[]> entry : imageMap.entrySet()) {
|
||||
int dataRowIndex = entry.getKey();
|
||||
int rowIndex = dataRowIndex + 1; // 跳过标题行
|
||||
byte[] imageData = entry.getValue();
|
||||
|
||||
if (imageData != null && imageData.length > 0) {
|
||||
insertImage(workbook, sheet, rowIndex, imageData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void insertImage(Workbook workbook, Sheet sheet, int rowIndex, byte[] imageData) {
|
||||
try {
|
||||
// 获取或创建行(确保行存在)
|
||||
Row row = sheet.getRow(rowIndex);
|
||||
if (row == null) {
|
||||
row = sheet.createRow(rowIndex);
|
||||
}
|
||||
|
||||
// 设置合适的行高(不要设置过大)
|
||||
row.setHeightInPoints(60); // 60磅,足够显示小图
|
||||
|
||||
// 添加图片到工作簿
|
||||
int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);
|
||||
|
||||
// 创建绘图对象
|
||||
Drawing<?> drawing = sheet.createDrawingPatriarch();
|
||||
|
||||
// 关键修改:使用MOVE_DONT_RESIZE锚点类型,避免影响行高
|
||||
ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
|
||||
anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
|
||||
anchor.setCol1(imageColIndex);
|
||||
anchor.setRow1(rowIndex);
|
||||
anchor.setCol2(imageColIndex + 1);
|
||||
anchor.setRow2(rowIndex + 1);
|
||||
|
||||
// 设置较小的偏移量,确保图片在单元格内
|
||||
anchor.setDx1(0);
|
||||
anchor.setDy1(0);
|
||||
anchor.setDx2(512 * 5); // 约5个字符宽度
|
||||
anchor.setDy2(256 * 4); // 约4行高度
|
||||
|
||||
// 插入图片
|
||||
Picture picture = drawing.createPicture(anchor, pictureIdx);
|
||||
|
||||
// 不要调用resize(),避免自动调整影响行高
|
||||
// picture.resize();
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("插入图片失败,行: " + rowIndex);
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
|
||||
// 不需要实现
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
|
||||
Workbook workbook = writeWorkbookHolder.getWorkbook();
|
||||
Sheet sheet = writeSheetHolder.getSheet();
|
||||
|
||||
// 获取设备图片列索引(假设是第4列,索引3)
|
||||
int imageColIndex = 3;
|
||||
|
||||
// 遍历所有行
|
||||
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { // 从第2行开始(跳过标题)
|
||||
Row row = sheet.getRow(rowIndex);
|
||||
if (row == null) continue;
|
||||
|
||||
Cell imageCell = row.getCell(imageColIndex);
|
||||
if (imageCell == null) continue;
|
||||
|
||||
// 获取图片数据
|
||||
byte[] imageData = null;
|
||||
if (imageCell.getCellType() == CellType.STRING) {
|
||||
// 处理Base64编码的图片(如果需要)
|
||||
}
|
||||
|
||||
if (imageData != null && imageData.length > 0) {
|
||||
try {
|
||||
// 添加图片到工作表
|
||||
int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);
|
||||
|
||||
// 创建绘图对象
|
||||
if (sheet instanceof XSSFSheet) {
|
||||
XSSFSheet xssfSheet = (XSSFSheet) sheet;
|
||||
XSSFDrawing drawing = xssfSheet.createDrawingPatriarch();
|
||||
|
||||
// 设置图片位置
|
||||
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, imageColIndex, rowIndex, imageColIndex + 1, rowIndex + 1);
|
||||
|
||||
// 创建图片
|
||||
drawing.createPicture(anchor, pictureIdx);
|
||||
}
|
||||
|
||||
// 清除单元格内容
|
||||
imageCell.setBlank();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -137,4 +137,13 @@ public interface DeviceMapper extends BaseMapper<Device> {
|
||||
List<DeviceUsageFrequencyVo> getDeviceUsageFrequency(@Param("days") int days);
|
||||
|
||||
List<OnlineStatusVo> queryOnlineStatusList();
|
||||
|
||||
/**
|
||||
* 根据设备类型ID查询设备数量
|
||||
*
|
||||
* @param deviceTypeId 设备类型ID
|
||||
* @return 设备数量
|
||||
*/
|
||||
int countByDeviceTypeId(@Param("deviceTypeId") Long deviceTypeId);
|
||||
|
||||
}
|
||||
@ -51,4 +51,13 @@ public interface DeviceTypeMapper extends BaseMapper<DeviceType> {
|
||||
*/
|
||||
DeviceType queryByName(@Param("criteria") DeviceTypeQueryCriteria criteria);
|
||||
|
||||
/**
|
||||
* 根据名称列表查询设备类型
|
||||
*
|
||||
* @param typeNames
|
||||
* @return
|
||||
*/
|
||||
List<DeviceType> selectByNames(@Param("typeNames") List<String> typeNames);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -49,6 +49,15 @@ public interface DeviceTypeService extends IService<DeviceType> {
|
||||
*/
|
||||
DeviceType queryByName(String typeName);
|
||||
|
||||
/**
|
||||
* 根据设备类型名称列表查询设备类型
|
||||
*
|
||||
* @param typeNames 设备类型名称列表
|
||||
* @return List<DeviceType>
|
||||
*/
|
||||
List<DeviceType> queryByNames(List<String> typeNames);
|
||||
|
||||
|
||||
/**
|
||||
* 新增设备类型
|
||||
*
|
||||
|
||||
@ -3,18 +3,20 @@ package com.fuyuanshen.equipment.service.impl;
|
||||
import com.alibaba.excel.EasyExcel;
|
||||
import com.alibaba.excel.util.DateUtils;
|
||||
import com.fuyuanshen.equipment.domain.Device;
|
||||
import com.fuyuanshen.equipment.domain.DeviceType;
|
||||
import com.fuyuanshen.equipment.domain.dto.DeviceExcelExportDTO;
|
||||
import com.fuyuanshen.equipment.domain.dto.DeviceWithTypeExcelExportDTO;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@ -26,6 +28,9 @@ import java.util.stream.Collectors;
|
||||
public class DeviceExportService {
|
||||
|
||||
public void export(List<Device> devices, HttpServletResponse response) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("开始导出设备列表,设备数量: {}", devices.size());
|
||||
|
||||
try {
|
||||
String fileName = "设备列表_" + System.currentTimeMillis() + ".xlsx";
|
||||
// 使用URLEncoder进行RFC 5987编码
|
||||
@ -36,26 +41,20 @@ public class DeviceExportService {
|
||||
// 使用RFC 5987标准编码文件名
|
||||
response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + encodedFileName);
|
||||
|
||||
// 转换为DTO列表
|
||||
List<DeviceExcelExportDTO> dtoList = devices.stream().map(device -> {
|
||||
// 转换为DTO列表,使用并行流加速处理
|
||||
List<DeviceExcelExportDTO> dtoList = devices.parallelStream().map(device -> {
|
||||
long deviceProcessStartTime = System.currentTimeMillis();
|
||||
DeviceExcelExportDTO dto = new DeviceExcelExportDTO();
|
||||
// dto.setId(device.getId());
|
||||
// dto.setDeviceType(device.getDeviceType());
|
||||
// dto.setCustomerName(device.getCustomerName());
|
||||
dto.setDeviceName(device.getDeviceName());
|
||||
dto.setDeviceMac(device.getDeviceMac());
|
||||
// 设备IMEI
|
||||
dto.setDeviceImei(device.getDeviceImei());
|
||||
// 蓝牙名称
|
||||
dto.setBluetoothName(device.getBluetoothName());
|
||||
// dto.setLongitude(device.getLongitude());
|
||||
// dto.setLatitude(device.getLatitude());
|
||||
dto.setRemark(device.getRemark());
|
||||
dto.setTypeName(device.getTypeName());
|
||||
dto.setCreateBy(device.getCreateByName());
|
||||
Integer deviceStatus = device.getDeviceStatus();
|
||||
Integer bindingStatus = device.getBindingStatus();
|
||||
// dto.setDeviceStatus(deviceStatus == 1 ? "正常" : "失效");
|
||||
dto.setBindingStatus(bindingStatus == 1 ? "已绑定" : "未绑定");
|
||||
// 时间戳转换
|
||||
dto.setCreateTime(DateUtils.format(device.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
|
||||
@ -63,54 +62,270 @@ public class DeviceExportService {
|
||||
// 处理图片URL转换
|
||||
handleDevicePic(device, dto);
|
||||
|
||||
long deviceProcessEndTime = System.currentTimeMillis();
|
||||
log.info("单个设备处理耗时: {} ms, 设备ID: {}", (deviceProcessEndTime - deviceProcessStartTime), device.getId());
|
||||
return dto;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
// 写入Excel
|
||||
long excelWriteStartTime = System.currentTimeMillis();
|
||||
EasyExcel.write(response.getOutputStream(), DeviceExcelExportDTO.class).sheet("设备数据").doWrite(dtoList);
|
||||
long excelWriteEndTime = System.currentTimeMillis();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("设备列表导出完成,总耗时: {} ms,设备数量: {},Excel写入耗时: {} ms",
|
||||
(endTime - startTime), devices.size(), (excelWriteEndTime - excelWriteStartTime));
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("导出Excel失败", e);
|
||||
throw new RuntimeException("导出Excel失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 导出设备数据(包含完整设备类型信息)
|
||||
*
|
||||
* @param devices
|
||||
* @param deviceTypes
|
||||
* @param response
|
||||
*/
|
||||
public void exportWithTypeInfo(List<Device> devices, List<DeviceType> deviceTypes, HttpServletResponse response) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("开始导出设备列表(含类型详情),设备数量: {}", devices.size());
|
||||
|
||||
try {
|
||||
String fileName = "设备列表_含类型详情_" + System.currentTimeMillis() + ".xlsx";
|
||||
// 使用URLEncoder进行RFC 5987编码
|
||||
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
|
||||
|
||||
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
response.setCharacterEncoding("utf-8");
|
||||
// 使用RFC 5987标准编码文件名
|
||||
response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + encodedFileName);
|
||||
|
||||
// 构建设备类型映射
|
||||
Map<Long, DeviceType> deviceTypeMap = deviceTypes.stream()
|
||||
.collect(Collectors.toMap(DeviceType::getId, deviceType -> deviceType));
|
||||
|
||||
// 转换为DTO列表,使用并行流加速处理
|
||||
List<DeviceWithTypeExcelExportDTO> dtoList = devices.parallelStream().map(device -> {
|
||||
long deviceProcessStartTime = System.currentTimeMillis();
|
||||
DeviceWithTypeExcelExportDTO dto = new DeviceWithTypeExcelExportDTO();
|
||||
dto.setDeviceName(device.getDeviceName());
|
||||
dto.setDeviceMac(device.getDeviceMac());
|
||||
// 设备IMEI
|
||||
dto.setDeviceImei(device.getDeviceImei());
|
||||
// 蓝牙名称
|
||||
dto.setBluetoothName(device.getBluetoothName());
|
||||
dto.setRemark(device.getRemark());
|
||||
dto.setTypeName(device.getTypeName());
|
||||
dto.setCreateBy(device.getCreateByName());
|
||||
Integer bindingStatus = device.getBindingStatus();
|
||||
dto.setBindingStatus(bindingStatus == 1 ? "已绑定" : "未绑定");
|
||||
// 时间戳转换
|
||||
dto.setCreateTime(DateUtils.format(device.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
// 获取设备类型详细信息
|
||||
DeviceType deviceType = deviceTypeMap.get(device.getDeviceType());
|
||||
if (deviceType != null) {
|
||||
// 处理是否支持蓝牙
|
||||
if (deviceType.getIsSupportBle() != null) {
|
||||
dto.setIsSupportBle(deviceType.getIsSupportBle() ? "是" : "否");
|
||||
} else {
|
||||
dto.setIsSupportBle("未知");
|
||||
}
|
||||
|
||||
// 处理定位方式
|
||||
if (deviceType.getLocateMode() != null) {
|
||||
dto.setLocateMode(convertLocateMode(deviceType.getLocateMode()));
|
||||
} else {
|
||||
dto.setLocateMode("");
|
||||
}
|
||||
|
||||
// 处理通讯方式
|
||||
if (deviceType.getCommunicationMode() != null) {
|
||||
dto.setCommunicationMode(convertCommunicationMode(deviceType.getCommunicationMode()));
|
||||
} else {
|
||||
dto.setCommunicationMode("");
|
||||
}
|
||||
|
||||
// 处理APP页面跳转字典
|
||||
dto.setAppModelDictionary(deviceType.getAppModelDictionary() != null ? deviceType.getAppModelDictionary() : "");
|
||||
|
||||
// 处理PC页面跳转字典
|
||||
dto.setPcModelDictionary(deviceType.getPcModelDictionary() != null ? deviceType.getPcModelDictionary() : "");
|
||||
} else {
|
||||
dto.setIsSupportBle("未知");
|
||||
dto.setLocateMode("");
|
||||
dto.setCommunicationMode("");
|
||||
dto.setAppModelDictionary("");
|
||||
dto.setPcModelDictionary("");
|
||||
}
|
||||
|
||||
// 处理图片URL转换
|
||||
handleDevicePicForTypeExport(device, dto);
|
||||
return dto;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
// 写入Excel
|
||||
long excelWriteStartTime = System.currentTimeMillis();
|
||||
EasyExcel.write(response.getOutputStream(), DeviceWithTypeExcelExportDTO.class).sheet("设备数据含类型详情").doWrite(dtoList);
|
||||
long excelWriteEndTime = System.currentTimeMillis();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("设备列表(含类型详情)导出完成,总耗时: {} ms,设备数量: {},Excel写入耗时: {} ms",
|
||||
(endTime - startTime), devices.size(), (excelWriteEndTime - excelWriteStartTime));
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("导出Excel失败", e);
|
||||
throw new RuntimeException("导出Excel失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 转换定位方式代码为中文描述
|
||||
*
|
||||
* @param locateMode 定位方式代码 (0:无;1:GPS;2:基站;3:wifi;4:北斗)
|
||||
* @return 中文描述
|
||||
*/
|
||||
private String convertLocateMode(String locateMode) {
|
||||
switch (locateMode) {
|
||||
case "0":
|
||||
return "无";
|
||||
case "1":
|
||||
return "GPS";
|
||||
case "2":
|
||||
return "基站";
|
||||
case "3":
|
||||
return "wifi";
|
||||
case "4":
|
||||
return "北斗";
|
||||
default:
|
||||
return locateMode;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换联网方式代码为中文描述
|
||||
*
|
||||
* @param networkWay 联网方式代码 (0:无;1:4G;2:WIFI)
|
||||
* @return 中文描述
|
||||
*/
|
||||
private String convertNetworkWay(String networkWay) {
|
||||
switch (networkWay) {
|
||||
case "0":
|
||||
return "无";
|
||||
case "1":
|
||||
return "4G";
|
||||
case "2":
|
||||
return "WIFI";
|
||||
default:
|
||||
return networkWay;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换通讯方式代码为中文描述
|
||||
*
|
||||
* @param communicationMode 通讯方式代码 (0:4G;1:蓝牙)
|
||||
* @return 中文描述
|
||||
*/
|
||||
private String convertCommunicationMode(String communicationMode) {
|
||||
switch (communicationMode) {
|
||||
case "0":
|
||||
return "4G";
|
||||
case "1":
|
||||
return "蓝牙";
|
||||
case "2":
|
||||
return "4G&蓝牙";
|
||||
default:
|
||||
return communicationMode;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 在DeviceExportService中添加并发控制
|
||||
private static final Semaphore imageLoadSemaphore = new Semaphore(5); // 最多同时加载5张图片
|
||||
private static final Semaphore imageLoadSemaphore = new Semaphore(10); // 增加到最多同时加载10张图片
|
||||
|
||||
private void handleDevicePic(Device device, DeviceExcelExportDTO dto) {
|
||||
String picUrl = device.getDevicePic();
|
||||
log.debug("处理设备图片,设备ID: {}, 图片URL: {}", device.getId(), picUrl);
|
||||
|
||||
if (picUrl != null && !picUrl.trim().isEmpty()) {
|
||||
try {
|
||||
// 获取加载图片的许可
|
||||
imageLoadSemaphore.acquire();
|
||||
// 获取加载图片的许可,带超时控制
|
||||
if (!imageLoadSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
|
||||
dto.setDevicePic(null);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 自动将HTTP转换为HTTPS以避免重定向问题
|
||||
if (picUrl.startsWith("http://")) {
|
||||
picUrl = "https://" + picUrl.substring(7);
|
||||
log.debug("自动将HTTP转换为HTTPS: {}", picUrl);
|
||||
}
|
||||
|
||||
// 尝试创建URL对象(会自动验证格式)
|
||||
URL url = new URL(picUrl);
|
||||
dto.setDevicePic(url);
|
||||
log.debug("成功设置设备图片URL到DTO");
|
||||
} finally {
|
||||
// 释放许可
|
||||
imageLoadSemaphore.release();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("设置设备图片失败,设备ID: {}, URL: {}, 错误: {}", device.getId(), picUrl, e.getMessage());
|
||||
dto.setDevicePic(null);
|
||||
}
|
||||
} else {
|
||||
log.debug("设备没有设置图片,设备ID: {}", device.getId());
|
||||
dto.setDevicePic(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void handleDevicePicForTypeExport(Device device, DeviceWithTypeExcelExportDTO dto) {
|
||||
String picUrl = device.getDevicePic();
|
||||
|
||||
if (picUrl != null && !picUrl.trim().isEmpty()) {
|
||||
try {
|
||||
// 获取加载图片的许可,带超时控制
|
||||
if (!imageLoadSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
|
||||
dto.setDevicePic(null);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
picUrl = convertUrl(picUrl);
|
||||
|
||||
// 尝试创建URL对象(会自动验证格式)
|
||||
URL url = new URL(picUrl);
|
||||
dto.setDevicePic(url);
|
||||
|
||||
} finally {
|
||||
// 释放许可
|
||||
imageLoadSemaphore.release();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
dto.setDevicePic(null);
|
||||
}
|
||||
} else {
|
||||
dto.setDevicePic(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换图片URL为HTTP
|
||||
* 转回minio格式
|
||||
*
|
||||
* @param originalUrl 原始URL
|
||||
* @return 转换后的URL
|
||||
*/
|
||||
|
||||
public String convertUrl(String originalUrl) {
|
||||
String result = originalUrl.replace("https://fuyuanshen.com", "http://120.79.224.186:9000");
|
||||
result = result.replace("http://fuyuanshen.com", "http://120.79.224.186:9000");
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -50,6 +50,7 @@ public class DeviceRepairRecordsServiceImpl extends ServiceImpl<DeviceRepairReco
|
||||
private final DeviceRepairRecordsMapper baseMapper;
|
||||
private final DeviceRepairImagesMapper imagesMapper;
|
||||
private final ISysOssService ossService;
|
||||
private final FileHashUtil fileHashUtil;
|
||||
|
||||
/**
|
||||
* 查询设备维修记录
|
||||
@ -210,19 +211,13 @@ public class DeviceRepairRecordsServiceImpl extends ServiceImpl<DeviceRepairReco
|
||||
// 1. 计算文件哈希
|
||||
String hash = null;
|
||||
try {
|
||||
hash = FileHashUtil.hash(file);
|
||||
hash = fileHashUtil.hash(file);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
// 2. 先根据 hash 查库(秒传)
|
||||
SysOssVo exist = ossService.selectByHash(hash);
|
||||
if (exist == null) {
|
||||
// 2.2 不存在,真正上传
|
||||
exist = ossService.upload(file);
|
||||
// 2.3 把 hash 写回记录(供下次去重)
|
||||
ossService.updateHashById(exist.getOssId(), hash);
|
||||
}
|
||||
SysOssVo exist = ossService.updateHash(file,hash);
|
||||
|
||||
DeviceRepairImages image = new DeviceRepairImages();
|
||||
image.setRecordId(recordId);
|
||||
|
||||
@ -19,11 +19,8 @@ import com.fuyuanshen.common.satoken.utils.AppLoginHelper;
|
||||
import com.fuyuanshen.common.satoken.utils.LoginHelper;
|
||||
import com.fuyuanshen.customer.domain.Customer;
|
||||
import com.fuyuanshen.customer.mapper.CustomerMapper;
|
||||
import com.fuyuanshen.equipment.constants.DeviceConstants;
|
||||
import com.fuyuanshen.equipment.domain.*;
|
||||
import com.fuyuanshen.equipment.domain.bo.DeviceFenceAccessRecordBo;
|
||||
import com.fuyuanshen.equipment.domain.dto.AppDeviceBo;
|
||||
import com.fuyuanshen.equipment.domain.dto.FenceCheckResponse;
|
||||
import com.fuyuanshen.equipment.domain.form.DeviceForm;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceAssignmentQuery;
|
||||
import com.fuyuanshen.equipment.domain.query.DeviceQueryCriteria;
|
||||
@ -33,22 +30,22 @@ import com.fuyuanshen.equipment.enums.BindingStatusEnum;
|
||||
import com.fuyuanshen.equipment.enums.CommunicationModeEnum;
|
||||
import com.fuyuanshen.equipment.enums.DeviceActiveStatusEnum;
|
||||
import com.fuyuanshen.equipment.mapper.*;
|
||||
import com.fuyuanshen.equipment.service.*;
|
||||
import com.fuyuanshen.equipment.service.DeviceAssignmentsService;
|
||||
import com.fuyuanshen.equipment.service.DeviceService;
|
||||
import com.fuyuanshen.equipment.service.DeviceTypeGrantsService;
|
||||
import com.fuyuanshen.equipment.service.IDeviceGeoFenceService;
|
||||
import com.fuyuanshen.equipment.utils.FileHashUtil;
|
||||
import com.fuyuanshen.system.domain.vo.SysOssVo;
|
||||
import com.fuyuanshen.system.domain.vo.SysRoleVo;
|
||||
import com.fuyuanshen.system.service.ISysOssService;
|
||||
import com.fuyuanshen.system.service.ISysRoleService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@ -66,11 +63,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
|
||||
private final ISysRoleService roleService;
|
||||
|
||||
@Value("${file.device.pic}")
|
||||
private String filePath;
|
||||
@Value("${file.device.ip}")
|
||||
private String ip;
|
||||
|
||||
private final DeviceMapper deviceMapper;
|
||||
private final DeviceTypeMapper deviceTypeMapper;
|
||||
private final CustomerMapper customerMapper;
|
||||
@ -84,6 +76,7 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
private final DeviceTypeGrantsMapper deviceTypeGrantsMapper;
|
||||
|
||||
private final DeviceFenceAccessRecordMapper deviceFenceAccessRecordMapper;
|
||||
private final FileHashUtil fileHashUtil;
|
||||
|
||||
|
||||
/**
|
||||
@ -195,21 +188,108 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
throw new BadRequestException("设备IMEI已存在!!!");
|
||||
}
|
||||
|
||||
DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
|
||||
queryCriteria.setDeviceTypeId(deviceForm.getDeviceType());
|
||||
queryCriteria.setCustomerId(LoginHelper.getUserId());
|
||||
DeviceTypeGrants typeGrants = deviceTypeGrantsMapper.selectById(queryCriteria.getDeviceTypeId());
|
||||
if (typeGrants == null) {
|
||||
throw new Exception("设备类型不存在!!!");
|
||||
DeviceTypeGrants typeGrants = new DeviceTypeGrants();
|
||||
|
||||
if (deviceForm.getDeviceType() != null) {
|
||||
DeviceTypeQueryCriteria queryCriteria = new DeviceTypeQueryCriteria();
|
||||
queryCriteria.setDeviceTypeId(deviceForm.getDeviceType());
|
||||
typeGrants = deviceTypeGrantsMapper.selectById(queryCriteria.getDeviceTypeId());
|
||||
if (typeGrants == null) {
|
||||
throw new Exception("设备类型不存在!!!");
|
||||
}
|
||||
}
|
||||
DeviceType deviceTypes = deviceTypeMapper.selectById(typeGrants.getDeviceTypeId());
|
||||
if (deviceTypes == null) {
|
||||
|
||||
// 检查设备类型是否存在,如果不存在则创建
|
||||
DeviceType deviceType = null;
|
||||
if (deviceForm.getDeviceType() != null) {
|
||||
deviceType = deviceTypeMapper.selectById(typeGrants.getDeviceTypeId());
|
||||
} else if (deviceForm.getTypeName() != null) {
|
||||
deviceType = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("type_name", deviceForm.getTypeName()));
|
||||
}
|
||||
|
||||
if (deviceType == null && deviceForm.getTypeName() != null) {
|
||||
// 创建新的设备类型
|
||||
DeviceType newDeviceType = new DeviceType();
|
||||
newDeviceType.setTypeName(deviceForm.getTypeName());
|
||||
newDeviceType.setIsSupportBle("是".equals(deviceForm.getIsSupportBle()) || "1".equals(deviceForm.getIsSupportBle()));
|
||||
|
||||
// 设置定位方式
|
||||
if (deviceForm.getLocateMode() != null) {
|
||||
switch (deviceForm.getLocateMode()) {
|
||||
case "无":
|
||||
newDeviceType.setLocateMode("0");
|
||||
break;
|
||||
case "GPS":
|
||||
newDeviceType.setLocateMode("1");
|
||||
break;
|
||||
case "基站":
|
||||
newDeviceType.setLocateMode("2");
|
||||
break;
|
||||
case "wifi":
|
||||
newDeviceType.setLocateMode("3");
|
||||
break;
|
||||
case "北斗":
|
||||
newDeviceType.setLocateMode("4");
|
||||
break;
|
||||
default:
|
||||
newDeviceType.setLocateMode(deviceForm.getLocateMode());
|
||||
}
|
||||
}
|
||||
|
||||
// 设置通讯方式
|
||||
if (deviceForm.getCommunicationMode() != null) {
|
||||
switch (deviceForm.getCommunicationMode()) {
|
||||
case "4G":
|
||||
newDeviceType.setCommunicationMode("0");
|
||||
break;
|
||||
case "蓝牙":
|
||||
newDeviceType.setCommunicationMode("1");
|
||||
break;
|
||||
case "4G&蓝牙":
|
||||
newDeviceType.setCommunicationMode("2");
|
||||
break;
|
||||
default:
|
||||
newDeviceType.setCommunicationMode(deviceForm.getCommunicationMode());
|
||||
}
|
||||
}
|
||||
|
||||
newDeviceType.setAppModelDictionary(deviceForm.getAppModelDictionary());
|
||||
newDeviceType.setPcModelDictionary(deviceForm.getPcModelDictionary());
|
||||
|
||||
// 校验设备类型名称
|
||||
List<DeviceType> existingTypes = deviceTypeMapper.selectList(new QueryWrapper<DeviceType>().eq("type_name", newDeviceType.getTypeName()));
|
||||
if (CollectionUtil.isNotEmpty(existingTypes)) {
|
||||
throw new RuntimeException("设备类型名称已存在,无法新增!!!");
|
||||
}
|
||||
|
||||
LoginUser loginUser = LoginHelper.getLoginUser();
|
||||
newDeviceType.setCreateByName(loginUser.getNickname());
|
||||
deviceTypeMapper.insert(newDeviceType);
|
||||
|
||||
// 重新查询确保获取到正确的ID
|
||||
deviceType = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("type_name", deviceForm.getTypeName()));
|
||||
|
||||
// 自动授权给自己
|
||||
DeviceTypeGrants deviceTypeGrants = new DeviceTypeGrants();
|
||||
deviceTypeGrants.setDeviceTypeId(deviceType.getId());
|
||||
deviceTypeGrants.setCustomerId(loginUser.getUserId());
|
||||
deviceTypeGrants.setGrantorCustomerId(loginUser.getUserId());
|
||||
deviceTypeGrants.setGrantedAt(new Date());
|
||||
deviceTypeGrantsMapper.insert(deviceTypeGrants);
|
||||
}
|
||||
|
||||
if (deviceType == null) {
|
||||
throw new Exception("设备类型不存在!!!");
|
||||
}
|
||||
|
||||
// 保存图片并获取URL
|
||||
if (deviceForm.getFile() != null) {
|
||||
SysOssVo upload = ossService.upload(deviceForm.getFile());
|
||||
String fileHash = fileHashUtil.hash(deviceForm.getFile());
|
||||
SysOssVo upload = ossService.updateHash(deviceForm.getFile(), fileHash);
|
||||
// 强制将HTTP替换为HTTPS
|
||||
if (upload.getUrl() != null && upload.getUrl().startsWith("http://")) {
|
||||
upload.setUrl(upload.getUrl().replaceFirst("^http://", "https://"));
|
||||
}
|
||||
// 设置图片路径
|
||||
deviceForm.setDevicePic(upload.getUrl());
|
||||
}
|
||||
@ -223,8 +303,8 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
device.setCurrentOwnerId(loginUser.getUserId());
|
||||
device.setOriginalOwnerId(loginUser.getUserId());
|
||||
device.setCreateByName(loginUser.getNickname());
|
||||
device.setTypeName(deviceTypes.getTypeName());
|
||||
device.setDeviceType(deviceTypes.getId());
|
||||
device.setTypeName(deviceType.getTypeName());
|
||||
device.setDeviceType(deviceType.getId());
|
||||
if (device.getDeviceImei() != null) {
|
||||
device.setPubTopic("A/" + device.getDeviceImei());
|
||||
device.setSubTopic("B/" + device.getDeviceImei());
|
||||
@ -283,8 +363,8 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
|
||||
// 处理上传的图片
|
||||
if (deviceForm.getFile() != null) {
|
||||
// 设置图片路径
|
||||
SysOssVo oss = ossService.upload(deviceForm.getFile());
|
||||
String fileHash = fileHashUtil.hash(deviceForm.getFile());
|
||||
SysOssVo oss = ossService.updateHash(deviceForm.getFile(), fileHash);
|
||||
// 强制将HTTP替换为HTTPS
|
||||
if (oss.getUrl() != null && oss.getUrl().startsWith("http://")) {
|
||||
oss.setUrl(oss.getUrl().replaceFirst("^http://", "https://"));
|
||||
@ -301,35 +381,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 保存设备图片并返回访问路径
|
||||
*
|
||||
* @param file MultipartFile
|
||||
* @param deviceMac 设备MAC用于生成唯一文件名
|
||||
* @return 文件存储路径 URL 形式
|
||||
*/
|
||||
private String saveDeviceImage(MultipartFile file, String deviceMac) throws IOException {
|
||||
if (file == null || file.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String originalFileName = file.getOriginalFilename();
|
||||
String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
|
||||
String newFileName = "PS_" + deviceMac + "." + fileExtension;
|
||||
|
||||
File newFile = new File(filePath + DeviceConstants.FILE_ACCESS_ISOLATION + File.separator + newFileName);
|
||||
|
||||
if (!newFile.getParentFile().exists()) {
|
||||
newFile.getParentFile().mkdirs();
|
||||
}
|
||||
|
||||
log.info("图片保存路径: {}", newFile.getAbsolutePath());
|
||||
file.transferTo(newFile);
|
||||
|
||||
return ip + DeviceConstants.FILE_ACCESS_PREFIX + "/" + DeviceConstants.FILE_ACCESS_ISOLATION + "/" + newFileName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除设备
|
||||
*
|
||||
|
||||
@ -159,6 +159,21 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据设备类型名称列表查询设备类型
|
||||
*
|
||||
* @param typeNames 设备类型名称列表
|
||||
* @return List<DeviceType>
|
||||
*/
|
||||
@Override
|
||||
public List<DeviceType> queryByNames(List<String> typeNames) {
|
||||
if (typeNames == null || typeNames.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return deviceTypeMapper.selectByNames(typeNames);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 新增设备类型
|
||||
*
|
||||
@ -209,6 +224,16 @@ public class DeviceTypeServiceImpl extends ServiceImpl<DeviceTypeMapper, DeviceT
|
||||
throw new RuntimeException("设备类型不存在");
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (!deviceType.getTypeName().equals(resources.getTypeName())) {
|
||||
int count = deviceMapper.countByDeviceTypeId(deviceType.getId());
|
||||
if (count > 0) {
|
||||
throw new RuntimeException("该设备类型下已有绑定设备,无法修改设备类型名称!!!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>()
|
||||
// .eq("device_type", deviceTypeGrants.getDeviceTypeId()));
|
||||
// if (CollectionUtil.isNotEmpty(devices)) {
|
||||
|
||||
@ -1,28 +1,70 @@
|
||||
package com.fuyuanshen.equipment.utils;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* 文件哈希工具类
|
||||
*/
|
||||
@Component // 如果使用 Spring 可以注入
|
||||
public class FileHashUtil {
|
||||
/* 算法常量 */
|
||||
private static final String ALGORITHM = "SHA-256";
|
||||
/* 缓冲区大小 8 KB */
|
||||
private static final int BUFFER_SIZE = 8192;
|
||||
|
||||
public static String hash(MultipartFile file) throws IOException {
|
||||
MessageDigest digest = DigestUtils.getDigest(ALGORITHM);
|
||||
/**
|
||||
* 计算上传文件的 SHA-256 十六进制哈希
|
||||
*
|
||||
* @param file 上传文件;不能为 null,且必须非空
|
||||
* @return 64 位小写十六进制字符串
|
||||
* @throws IllegalArgumentException 参数不合法
|
||||
* @throws IOException 流读取失败
|
||||
* @throws IllegalStateException 算法运行时异常(不会触发)
|
||||
*/
|
||||
public String hash(MultipartFile file) throws IOException {
|
||||
validate(file);
|
||||
|
||||
/* 每个请求新建实例,保证线程安全 */
|
||||
MessageDigest digest = newDigest();
|
||||
|
||||
/* try-with-resources 自动关闭流 */
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
byte[] buf = new byte[8192];
|
||||
byte[] buf = new byte[BUFFER_SIZE];
|
||||
int len;
|
||||
while ((len = in.read(buf)) != -1) {
|
||||
digest.update(buf, 0, len);
|
||||
}
|
||||
}
|
||||
|
||||
/* JDK 17+ 的 HexFormat,比 Apache Commons 更快且无需额外依赖 */
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
/* -------------------- 私有辅助方法 -------------------- */
|
||||
|
||||
private static void validate(MultipartFile file) {
|
||||
if (file == null) {
|
||||
throw new IllegalArgumentException("MultipartFile 不能为 null");
|
||||
}
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("上传文件不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
private static MessageDigest newDigest() {
|
||||
try {
|
||||
return MessageDigest.getInstance(ALGORITHM);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
/* SHA-256 是 JDK 必现算法,走到这里说明 JDK 实现损坏 */
|
||||
throw new IllegalStateException("算法 " + ALGORITHM + " 不可用", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -227,6 +227,7 @@
|
||||
FROM device
|
||||
WHERE original_device_id = #{originalDeviceId}
|
||||
</select>
|
||||
|
||||
<select id="getDeviceInfo" resultType="com.fuyuanshen.equipment.domain.vo.AppDeviceVo">
|
||||
select d.id,
|
||||
d.device_name,
|
||||
@ -244,6 +245,7 @@
|
||||
inner join device_type dt on d.device_type = dt.id
|
||||
where d.device_mac = #{deviceMac}
|
||||
</select>
|
||||
|
||||
<select id="queryWebDeviceList" resultType="com.fuyuanshen.equipment.domain.vo.WebDeviceVo">
|
||||
select * from (select d.id, d.device_name,
|
||||
d.device_mac,
|
||||
@ -495,4 +497,11 @@
|
||||
FROM device a left join device_type b on a.device_type = b.id where b.communication_mode in (0, 2) and a.online_status in (1,2)
|
||||
</select>
|
||||
|
||||
<!-- 根据设备类型ID查询设备数量 -->
|
||||
<select id="countByDeviceTypeId" resultType="int">
|
||||
SELECT COUNT(*)
|
||||
FROM device
|
||||
WHERE device_type = #{deviceTypeId}
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@ -58,4 +58,14 @@
|
||||
</where>
|
||||
</select>
|
||||
|
||||
<!-- 根据名称列表查询设备类型 -->
|
||||
<select id="selectByNames" resultMap="BaseResultMap">
|
||||
SELECT dt.*
|
||||
FROM device_type dt
|
||||
WHERE dt.type_name IN
|
||||
<foreach collection="typeNames" item="name" open="(" separator="," close=")">
|
||||
#{name}
|
||||
</foreach>
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@ -51,6 +51,7 @@ public class SysOss extends TenantEntity {
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
/**
|
||||
* 内容哈希
|
||||
*/
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user