若依微服务1.4.0

1、设备管理增加重启,并且只有网关和直连设备可以控制
2、数据处理完善对图片的处理
3、增加手机端的接口
4、tenantId写到header中,以便在保存数据时获取
5、角色管理租户可增删改查
dev 1.4.0
xins 1 year ago
parent 323c0072dc
commit 5d20ff6f48

@ -1,8 +1,13 @@
package com.ruoyi.system.api;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.system.api.domain.Base64FileVo;
import com.ruoyi.system.api.domain.SysOperLog;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.constant.ServiceNameConstants;
@ -26,4 +31,15 @@ public interface RemoteFileService
*/
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R<SysFile> upload(@RequestPart(value = "file") MultipartFile file);
/**
* @param: base64FileVo
* @description base64
* @author xins
* @date 2023-10-07 9:43
* @return R<SysFile>
*/
@PostMapping("/uploadBase64File")
public R<SysFile> uploadBase64File(@RequestBody Base64FileVo base64FileVo);
}

@ -0,0 +1,19 @@
package com.ruoyi.system.api.domain;
import lombok.Data;
/**
* @Description: base64
* @ClassName: Base64FileVo
* @Author : xins
* @Date :2023-10-07 9:36
* @Version :1.0
*/
@Data
public class Base64FileVo {
private String base64Str;//base64图片字符串
private String imagePath;//保存图片的前缀地址
private String extension;//图片后缀
}

@ -1,5 +1,6 @@
package com.ruoyi.system.api.factory;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
@ -30,6 +31,11 @@ public class RemoteFileFallbackFactory implements FallbackFactory<RemoteFileServ
{
return R.fail("上传文件失败:" + throwable.getMessage());
}
@Override
public R<SysFile> uploadBase64File(Base64FileVo base64FileVo) {
return R.fail("上传base64图片失败:" + throwable.getMessage());
}
};
}
}

@ -58,6 +58,8 @@ public class LoginUser implements Serializable
*/
private SysUser sysUser;
private Long tenantId;
public String getToken()
{
return token;
@ -147,4 +149,12 @@ public class LoginUser implements Serializable
{
this.sysUser = sysUser;
}
public Long getTenantId() {
return tenantId;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
}

@ -46,4 +46,9 @@ public class SecurityConstants
*
*/
public static final String ROLE_PERMISSION = "role_permission";
/**
* ID
*/
public static final String DETAILS_TENANTID = "tenantid";
}

@ -95,4 +95,15 @@ public class SecurityContextHolder
{
THREAD_LOCAL.remove();
}
public static Long getTenantId()
{
return Convert.toLong(get(SecurityConstants.DETAILS_TENANTID), 0L);
}
public static void setTenantId(String tenantIdStr)
{
set(SecurityConstants.DETAILS_TENANTID, tenantIdStr);
}
}

@ -109,6 +109,17 @@ public class JwtUtils
return getValue(claims, SecurityConstants.DETAILS_USERNAME);
}
/**
*
*
* @param claims
* @return
*/
public static String getTenantId(Claims claims)
{
return getValue(claims, SecurityConstants.DETAILS_TENANTID);
}
/**
*
*

@ -31,6 +31,7 @@ public class HeaderInterceptor implements AsyncHandlerInterceptor
SecurityContextHolder.setUserId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID));
SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME));
SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
SecurityContextHolder.setTenantId(ServletUtils.getHeader(request, SecurityConstants.DETAILS_TENANTID));
String token = SecurityUtils.getToken();
if (StringUtils.isNotEmpty(token))

@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.constant.CacheConstants;
@ -19,12 +20,11 @@ import com.ruoyi.system.api.model.LoginUser;
/**
* token
*
*
* @author ruoyi
*/
@Component
public class TokenService
{
public class TokenService {
@Autowired
private RedisService redisService;
@ -41,15 +41,16 @@ public class TokenService
/**
*
*/
public Map<String, Object> createToken(LoginUser loginUser)
{
public Map<String, Object> createToken(LoginUser loginUser) {
String token = IdUtils.fastUUID();
Long userId = loginUser.getSysUser().getUserId();
String userName = loginUser.getSysUser().getUserName();
Long tenantId = loginUser.getSysUser().getTenantId();
loginUser.setToken(token);
loginUser.setUserid(userId);
loginUser.setUsername(userName);
loginUser.setIpaddr(IpUtils.getIpAddr());
loginUser.setTenantId(tenantId);
refreshToken(loginUser);
// Jwt存储信息
@ -57,6 +58,7 @@ public class TokenService
claimsMap.put(SecurityConstants.USER_KEY, token);
claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
claimsMap.put(SecurityConstants.DETAILS_TENANTID, tenantId);
// 接口返回信息
Map<String, Object> rspMap = new HashMap<String, Object>();
@ -70,8 +72,7 @@ public class TokenService
*
* @return
*/
public LoginUser getLoginUser()
{
public LoginUser getLoginUser() {
return getLoginUser(ServletUtils.getRequest());
}
@ -80,8 +81,7 @@ public class TokenService
*
* @return
*/
public LoginUser getLoginUser(HttpServletRequest request)
{
public LoginUser getLoginUser(HttpServletRequest request) {
// 获取请求携带的令牌
String token = SecurityUtils.getToken(request);
return getLoginUser(token);
@ -92,20 +92,15 @@ public class TokenService
*
* @return
*/
public LoginUser getLoginUser(String token)
{
public LoginUser getLoginUser(String token) {
LoginUser user = null;
try
{
if (StringUtils.isNotEmpty(token))
{
try {
if (StringUtils.isNotEmpty(token)) {
String userkey = JwtUtils.getUserKey(token);
user = redisService.getCacheObject(getTokenKey(userkey));
return user;
}
}
catch (Exception e)
{
} catch (Exception e) {
}
return user;
}
@ -113,10 +108,8 @@ public class TokenService
/**
*
*/
public void setLoginUser(LoginUser loginUser)
{
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
{
public void setLoginUser(LoginUser loginUser) {
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
refreshToken(loginUser);
}
}
@ -124,10 +117,8 @@ public class TokenService
/**
*
*/
public void delLoginUser(String token)
{
if (StringUtils.isNotEmpty(token))
{
public void delLoginUser(String token) {
if (StringUtils.isNotEmpty(token)) {
String userkey = JwtUtils.getUserKey(token);
redisService.deleteObject(getTokenKey(userkey));
}
@ -138,12 +129,10 @@ public class TokenService
*
* @param loginUser
*/
public void verifyToken(LoginUser loginUser)
{
public void verifyToken(LoginUser loginUser) {
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
{
if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
refreshToken(loginUser);
}
}
@ -153,8 +142,7 @@ public class TokenService
*
* @param loginUser
*/
public void refreshToken(LoginUser loginUser)
{
public void refreshToken(LoginUser loginUser) {
loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存
@ -162,8 +150,7 @@ public class TokenService
redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
}
private String getTokenKey(String token)
{
private String getTokenKey(String token) {
return ACCESS_TOKEN + token;
}
}

@ -114,4 +114,12 @@ public class SecurityUtils
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
/**
* ID
*/
public static Long getTenantId()
{
return SecurityContextHolder.getTenantId();
}
}

@ -69,6 +69,7 @@ public class AuthFilter implements GlobalFilter, Ordered
}
String userid = JwtUtils.getUserId(claims);
String username = JwtUtils.getUserName(claims);
String tenantId = JwtUtils.getTenantId(claims);
if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username))
{
return unauthorizedResponse(exchange, "令牌验证失败");
@ -78,6 +79,7 @@ public class AuthFilter implements GlobalFilter, Ordered
addHeader(mutate, SecurityConstants.USER_KEY, userkey);
addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
addHeader(mutate, SecurityConstants.DETAILS_TENANTID, tenantId);
// 内部请求来源参数清除
removeHeader(mutate, SecurityConstants.FROM_SOURCE);
return chain.filter(exchange.mutate().request(mutate.build()).build());

@ -1,14 +1,26 @@
package com.ruoyi.business.controller;
import com.ruoyi.business.domain.HwAlarmInfo;
import com.ruoyi.business.domain.HwDevice;
import com.ruoyi.business.domain.HwMonitorUnit;
import com.ruoyi.business.domain.HwScene;
import com.ruoyi.business.domain.VO.AllNumsVo;
import com.ruoyi.business.service.IHwAlarmInfoService;
import com.ruoyi.business.service.IHwDeviceService;
import com.ruoyi.business.service.IHwMonitorUnitService;
import com.ruoyi.business.service.IHwSceneService;
import com.ruoyi.common.core.constant.HwDictConstants;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -25,16 +37,146 @@ public class HwAppController extends BaseController {
@Autowired
private IHwMonitorUnitService hwMonitorUnitService;
@Autowired
private IHwSceneService hwSceneService;
@Autowired
private IHwAlarmInfoService hwAlarmInfoService;
@Autowired
private IHwDeviceService hwDeviceService;
/**
*
*/
@GetMapping("/selectSecnes")
public AjaxResult selectSecnes(HwScene scene) {
List<HwScene> hwScenes = hwSceneService.selectHwSceneList(scene);
return success(hwScenes);
}
/**
* app
*/
@RequiresPermissions("business:monitor:standard")
@GetMapping("/sceneAllNums/{sceneId}")
public AllNumsVo sceneAllNums(@PathVariable("sceneId") Long sceneId) {
return hwMonitorUnitService.selectAllNums(sceneId);
}
/**
*
* ()
*/
@RequiresPermissions("business:monitorUnit:list")
@GetMapping("/monitorUnit/list")
public TableDataInfo monitorUnitList(HwMonitorUnit hwMonitorUnit)
{
@RequiresPermissions("business:monitor:standard")
@GetMapping("/limitSubMonitorUnit/{sceneId}")
public TableDataInfo limitSubMonitorUnit(@PathVariable("sceneId") Long sceneId) {
HwMonitorUnit hwMonitorUnit = new HwMonitorUnit();
hwMonitorUnit.setSceneId(sceneId);
startPage();
List<HwMonitorUnit> list = hwMonitorUnitService.selectHwMonitorUnitList(hwMonitorUnit);
return getDataTable(list);
List<HwMonitorUnit> hwMonitorUnits = hwMonitorUnitService.selectLimitSubMonitorUnit(hwMonitorUnit);
return getDataTable(hwMonitorUnits);
}
/**
* @return TableDataInfo
* @param: hwAlarmInfo
* @description
* @author xins
* @date 2023-09-15 11:03
*/
@GetMapping("/getAlarmInfos")
@RequiresPermissions("business:monitor:alarm")
public TableDataInfo getAlarmInfos(HwAlarmInfo hwAlarmInfo) {
hwAlarmInfo.setHandleStatus(HwDictConstants.ALARM_HANDLE_STATUS_NO);
List<HwAlarmInfo> alarmInfos = hwAlarmInfoService.selectHwAlarmInfoList(hwAlarmInfo);
return getDataTable(alarmInfos);
}
/**
* @param: hwAlarmInfo
* @description
* @author xins
* @date 2023-09-28 9:59
* @return AjaxResult
*/
@PutMapping("/handleAlarmInfo")
@RequiresPermissions("business:monitor:alarm")
public AjaxResult handleAlarmInfo(@RequestBody HwAlarmInfo hwAlarmInfo) {
hwAlarmInfo.setUpdateBy(SecurityUtils.getUsername());
return toAjax(hwAlarmInfoService.updateHwAlarmInfo(hwAlarmInfo));
}
/**
* ()
*
* @param sceneId ID
* @return list
* @throws
*/
@RequiresPermissions("business:monitor:deviceMonitor")
@GetMapping("/treeList/{sceneId}")
public AjaxResult monitorUnitTree(@PathVariable("sceneId") Long sceneId) {
HwMonitorUnit queryMonitorUnit = new HwMonitorUnit();
queryMonitorUnit.setSceneId(sceneId);
return success(hwMonitorUnitService.selectMonitorTreeList(queryMonitorUnit));
}
/**
* @param: monitorUnitId
* @description ID线线
* @author xins
* @date 2023-09-28 13:31
* @return AjaxResult
*/
@RequiresPermissions("business:monitor:deviceMonitor")
@GetMapping("/getDevicesInfoByMonitorUnitId/{monitorUnitId}")
public AjaxResult getDevicesInfoByMonitorUnitId(@PathVariable("monitorUnitId") Long monitorUnitId){
return success();
}
/**
* ID
*
* @param monitorUnitId id
*/
@RequiresPermissions("business:monitor:deviceMonitor")
@GetMapping("/selectDevicesByMonitorUnitId/{monitorUnitId}/{sceneId}")
public AjaxResult selectDeviceByDeviceModeByMonitorUnitId(@PathVariable("monitorUnitId") Long monitorUnitId,
@PathVariable("sceneId") Long sceneId) {
HwDevice queryHwDevice = new HwDevice();
queryHwDevice.setMonitorUnitId(monitorUnitId);
queryHwDevice.setSceneId(sceneId);
return success(hwDeviceService.getDevicesByMonitor(queryHwDevice));
}
/**
*
*/
@RequiresPermissions("business:device:add")
@Log(title = "设备信息(手机端)", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody HwDevice hwDevice) {
LoginUser loginUser = SecurityUtils.getLoginUser();
SysUser user = loginUser.getSysUser();
hwDevice.setTenantId(user.getTenantId());
hwDevice.setCreateBy(user.getUserName());
return toAjax(hwDeviceService.insertHwDevice(hwDevice));
}
/**
*
*
* @param deviceCode
*/
@RequiresPermissions("business:monitor:deviceMonitor")
@GetMapping("/getDeviceByDeviceCode/{deviceCode}")
public AjaxResult getDeviceByDeviceCode(@PathVariable("deviceCode") String deviceCode){
return success(hwDeviceService.selectHwDeviceByDeviceCode(deviceCode));
}
}

@ -169,10 +169,7 @@ public class HwMonitorPlatformController extends BaseController {
@RequiresPermissions("business:monitor:gps")
@GetMapping("/subDevice/{sceneId}")
public SubDeviceSumVo subDevice(@PathVariable("sceneId") Long sceneId) {
SubDeviceSumVo subDeviceSumVos = hwMonitorUnitService.selectSubDeviceSum(sceneId);
return subDeviceSumVos;
return hwMonitorUnitService.selectSubDeviceSum(sceneId);
}
@ -305,8 +302,7 @@ public class HwMonitorPlatformController extends BaseController {
/**
*
* id=0 id
*
*/
@GetMapping("/selectSecnes")
public AjaxResult selectSecnes(HwScene scene) {

@ -0,0 +1,21 @@
package com.ruoyi.business.domain.VO;
import lombok.Data;
/**
* @Description:
* @ClassName: DevicesInfoVo
* @Author : xins
* @Date :2023-09-28 14:21
* @Version :1.0
*/
@Data
public class DevicesInfoVo {
public int onlineDevicesCount;//设备在线数量
public int offlineDevicesCount;//设备离线数量
public int normalDevicesCount;//正常设备数量(无报警)
public int alarmDevicesCount;//报警设备数量
}

@ -66,4 +66,12 @@ public interface HwAlarmInfoMapper
public AlarmInfoVo selectAlarmCountByFenceArea(Long fenceAreaId);
/**
* @param: monitorUnitId
* @description ID
* @author xins
* @date 2023-09-28 14:17
* @return int
*/
public int selectAlarmCountByMonitorUnitId(Long monitorUnitId);
}

@ -76,6 +76,7 @@ public interface HwDeviceMapper
public int getOnlineDeviceNum(Long sceneId);
public HwDevice selectHwDeviceJoinByDeviceId(Long deviceId);
public List<HwDevice> selectLinkedDevices(Long deviceId);
@ -98,4 +99,13 @@ public interface HwDeviceMapper
* @return int
*/
public int checkExistSubDevice(Long releatedDeviceId);
/**
* @param: deviceCode
* @description
* @author xins
* @date 2023-09-28 13:23
* @return HwDevice
*/
public HwDevice selectHwDeviceByDeviceCode(String deviceCode);
}

@ -5,10 +5,7 @@ import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.HwDevice;
import com.ruoyi.business.domain.VO.DeviceControlVo;
import com.ruoyi.business.domain.VO.DeviceModeVo;
import com.ruoyi.business.domain.VO.HwDeviceVo;
import com.ruoyi.business.domain.VO.HwMonitorUnitVo;
import com.ruoyi.business.domain.VO.*;
import com.ruoyi.common.datascope.annotation.DataScope;
@ -130,6 +127,24 @@ public interface IHwDeviceService
*/
public void computeOnlineDevicecCount(int days);
/**
* @param: deviceControlVo
* @description
* @author xins
* @date 2023-09-25 14:56
*/
public void publishControlCommand(DeviceControlVo deviceControlVo);
/**
* @param: deviceCode
* @description
* @author xins
* @date 2023-09-28 13:24
* @return HwDevice
*/
public HwDevice selectHwDeviceByDeviceCode(String deviceCode);
/**
* @param: sceneId
* @description 线
@ -140,10 +155,11 @@ public interface IHwDeviceService
public JSONObject getOnlineDevicesCount(Long sceneId);
/**
* @param: deviceControlVo
* @description
* @param: monitorUnitId
* @description ID线线
* @author xins
* @date 2023-09-25 14:56
* @date 2023-09-28 14:25
* @return DevicesInfoVo
*/
public void publishControlCommand(DeviceControlVo deviceControlVo);
public DevicesInfoVo getDevicesInfoByMonitorUnitId(Long monitorUnitId);
}

@ -3,18 +3,12 @@ package com.ruoyi.business.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.ruoyi.business.domain.HwDevice;
import com.ruoyi.business.domain.HwDeviceMode;
import com.ruoyi.business.domain.HwDeviceModeFunction;
import com.ruoyi.business.domain.HwScene;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.VO.DeviceControlVo;
import com.ruoyi.business.domain.VO.DeviceModeVo;
import com.ruoyi.business.domain.VO.DevicesInfoVo;
import com.ruoyi.business.domain.VO.HwDeviceVo;
import com.ruoyi.business.mapper.HwDeviceMapper;
import com.ruoyi.business.mapper.HwDeviceModeFunctionMapper;
import com.ruoyi.business.mapper.HwDeviceModeMapper;
import com.ruoyi.business.mapper.HwSceneMapper;
import com.ruoyi.business.mapper.*;
import com.ruoyi.business.service.IHwDeviceService;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.HwDictConstants;
@ -35,6 +29,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
@ -57,6 +52,8 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
private RemoteTdEngineService remoteTdEngineService;
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private HwAlarmInfoMapper hwAlarmInfoMapper;
/**
*
@ -294,7 +291,6 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
}
for (int i = 0; i < list.size(); i++) {
list.get(i).setPercentage(NumberUtils.getPercentage(list.get(i).getSum(), sums));
System.out.println(list.get(i).toString());
}
@ -343,97 +339,6 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
return hwDeviceMapper.updateHwDevice(hwDevice);
}
/**
* @param: deviceControlVo
* @description
* @author xins
* @date 2023-09-25 14:56
*/
@Override
public void publishControlCommand(DeviceControlVo deviceControlVo) {
JSONObject controlCommandJson = new JSONObject();
StringBuilder controlCommandTopic = new StringBuilder();
Long deviceId = deviceControlVo.getDeviceId();
HwDevice device = hwDeviceMapper.selectHwDeviceByDeviceId(deviceId);
String deviceType = device.getDeviceType();
if (deviceType.equals(HwDictConstants.DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT)) {
Long gatewayDeviceId = device.getReleatedDeviceId();
HwDevice gatewayDevice = hwDeviceMapper.selectHwDeviceByDeviceId(gatewayDeviceId);
controlCommandTopic.append(StringUtils
.format(HwDictConstants.CONTROL_COMMAND_TOPIC_VALUE, gatewayDevice.getDeviceCode()));
} else {
controlCommandTopic.append(StringUtils
.format(HwDictConstants.CONTROL_COMMAND_TOPIC_VALUE, device.getDeviceCode()));
}
JSONObject payloadJson = new JSONObject();
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_MID_KEY, device.getDeviceCode());
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_TIMESTAMP_KEY, System.currentTimeMillis() / 1000);//单位s
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_TYPE_KEY, deviceControlVo.getType());
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_PARAM_KEY, "{}");
controlCommandJson.put(HwDictConstants.CONTROL_COMMAND_TOPIC_KEY, controlCommandTopic.toString());
controlCommandJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_KEY, payloadJson.toString());
System.out.println("---" + controlCommandJson.toString());
redisTemplate.convertAndSend(HwDictConstants.CONTROL_COMMAND_REDIS_KEY, controlCommandJson.toString());
}
/**
* @param: hwDevice
* @param: dbDevice
* @description TdEnginetag
* @author xins
* @date 2023-09-19 10:55
*/
private void updateTdEngine(HwDevice hwDevice, HwDevice dbDevice) {
String deviceType = hwDevice.getDeviceType();
String databaseName = TdEngineConstants.getDatabaseName(hwDevice.getSceneId());
String tableName = TdEngineConstants.getDeviceDataTableName(hwDevice.getDeviceId());
AlterTagVo alterTagVo = new AlterTagVo();
alterTagVo.setDatabaseName(databaseName);
alterTagVo.setTableName(tableName);
R<?> tdReturnMsg;
if (deviceType.equals(HwDictConstants.DEVICE_TYPE_DIRECT_CONNECT_DEVICE)
|| deviceType.equals(HwDictConstants.DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT)) {
if (!hwDevice.getDeviceCode().equals(dbDevice.getDeviceCode())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICECODE);
alterTagVo.setTagValue("'" + hwDevice.getDeviceCode() + "'");
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getDeviceName().equals(dbDevice.getDeviceName())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICENAME);
alterTagVo.setTagValue("'" + hwDevice.getDeviceName() + "'");
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getMonitorUnitId().equals(dbDevice.getMonitorUnitId())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_MONITORUNITID);
alterTagVo.setTagValue(hwDevice.getMonitorUnitId());
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getDeviceModeId().equals(dbDevice.getDeviceModeId())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICEMODEID);
alterTagVo.setTagValue(hwDevice.getDeviceModeId());
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
}
}
/**
*
*
@ -452,8 +357,7 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
* @return true false
*/
@Override
public boolean checkExistSubDevice(Long releatedDeviceId)
{
public boolean checkExistSubDevice(Long releatedDeviceId) {
int result = hwDeviceMapper.checkExistSubDevice(releatedDeviceId);
return result > 0;
}
@ -580,7 +484,6 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
return devicesMap;
}
/**
* ,join
*
@ -593,7 +496,6 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
return hwDeviceMapper.selectHwDeviceJoinList(hwDevice);
}
/**
* @param: days
* @description 线
@ -626,6 +528,185 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
redisTemplate.opsForValue().set(HwDictConstants.REDIS_KEY_ONLINE_DEVICE_COUNT_INFO, jsonObject.toString());
}
/**
* @param: deviceControlVo
* @description
* @author xins
* @date 2023-09-25 14:56
*/
@Override
public void publishControlCommand(DeviceControlVo deviceControlVo) {
JSONObject controlCommandJson = new JSONObject();
StringBuilder controlCommandTopic = new StringBuilder();
Long deviceId = deviceControlVo.getDeviceId();
HwDevice device = hwDeviceMapper.selectHwDeviceByDeviceId(deviceId);
String deviceType = device.getDeviceType();
if (deviceType.equals(HwDictConstants.DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT)) {
Long gatewayDeviceId = device.getReleatedDeviceId();
HwDevice gatewayDevice = hwDeviceMapper.selectHwDeviceByDeviceId(gatewayDeviceId);
controlCommandTopic.append(StringUtils
.format(HwDictConstants.CONTROL_COMMAND_TOPIC_VALUE, gatewayDevice.getDeviceCode()));
} else {
controlCommandTopic.append(StringUtils
.format(HwDictConstants.CONTROL_COMMAND_TOPIC_VALUE, device.getDeviceCode()));
}
JSONObject payloadJson = new JSONObject();
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_MID_KEY, device.getDeviceCode());
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_TIMESTAMP_KEY, System.currentTimeMillis() / 1000);//单位s
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_TYPE_KEY, deviceControlVo.getType());
payloadJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_PARAM_KEY, "{}");
controlCommandJson.put(HwDictConstants.CONTROL_COMMAND_TOPIC_KEY, controlCommandTopic.toString());
controlCommandJson.put(HwDictConstants.CONTROL_COMMAND_PAYLOAD_KEY, payloadJson.toString());
redisTemplate.convertAndSend(HwDictConstants.CONTROL_COMMAND_REDIS_KEY, controlCommandJson.toString());
}
/**
* @return HwDevice
* @param: deviceCode
* @description
* @author xins
* @date 2023-09-28 13:24
*/
@Override
public HwDevice selectHwDeviceByDeviceCode(String deviceCode) {
return hwDeviceMapper.selectHwDeviceByDeviceCode(deviceCode);
}
/**
* @return String
* @param: sceneId
* @description 线
* @author xins
* @date 2023-09-21 9:09
*/
@Override
public JSONObject getOnlineDevicesCount(Long sceneId) {
JSONObject returnObj = new JSONObject();
int onlineDevicesCount = hwDeviceMapper.getOnlineDeviceNum(sceneId);
JSONObject sortedJsonObject = new JSONObject();
String onlineDeviceCountJsonStr = redisTemplate.opsForValue().get(HwDictConstants.REDIS_KEY_ONLINE_DEVICE_COUNT_INFO);
if (onlineDeviceCountJsonStr != null) {
JSONObject jsonObject = JSONObject.parseObject(onlineDeviceCountJsonStr);
jsonObject.forEach((key, value) -> {
String dateStrKey = DateUtils.parseDateToStr(DateUtils.MM_DD, new Date(Long.parseLong(key)));
sortedJsonObject.put(dateStrKey, value);
});
}
returnObj.put("onlineDevicesTrend", sortedJsonObject);
returnObj.put("onlineDevicesCount", onlineDevicesCount);
return returnObj;
}
/**
* @param: monitorUnitId
* @description ID线线
* @author xins
* @date 2023-09-28 14:25
* @return DevicesInfoVo
*/
@Override
public DevicesInfoVo getDevicesInfoByMonitorUnitId(Long monitorUnitId) {
HwDevice queryDevice = new HwDevice();
queryDevice.setMonitorUnitId(monitorUnitId);
queryDevice.setDeviceStatus(HwDictConstants.DEVICE_STATUS_PUBLISH);
List<HwDevice> devices = this.selectHwDeviceList(queryDevice);
Map<String, List<HwDevice>> hwDevicesMap = devices.stream()
.collect(Collectors.groupingBy(HwDevice::getDeviceType));
List<HwDevice> gatewayDevices = hwDevicesMap.get(HwDictConstants.DEVICE_TYPE_GATEWAY_DEVICE);
List<HwDevice> subDevices = hwDevicesMap.get(HwDictConstants.DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT);
//根据关联网关设备ID进行分组
Map<Long, List<HwDevice>> releatedDeviceIdDevicesMap = subDevices.stream()
.collect(Collectors.groupingBy(HwDevice::getReleatedDeviceId));
int onlineDevicesCount = 0;
int offlineDevicesCount = 0;
for (HwDevice gatewayDevice : gatewayDevices) {
String onlineStatus = gatewayDevice.getOnlineStatus();
//获取关联子设备的数量
int gatewaySubPublishedDevicesCount =
releatedDeviceIdDevicesMap.get(gatewayDevice.getDeviceId()) == null ?
0 : releatedDeviceIdDevicesMap.get(gatewayDevice.getDeviceId()).size();
if (onlineStatus.equals(HwDictConstants.DEVICE_ONLINE_STATUS_ONLINE)) {
onlineDevicesCount += gatewaySubPublishedDevicesCount;
} else if (onlineStatus.equals(HwDictConstants.DEVICE_ONLINE_STATUS_OFFLINE)) {
offlineDevicesCount += gatewaySubPublishedDevicesCount;
}
}
int alarmDevicesCount = hwAlarmInfoMapper.selectAlarmCountByMonitorUnitId(monitorUnitId);
int normalDevicesCount = onlineDevicesCount + offlineDevicesCount - alarmDevicesCount;
DevicesInfoVo devicesInfoVo = new DevicesInfoVo();
devicesInfoVo.setOnlineDevicesCount(onlineDevicesCount);
devicesInfoVo.setOfflineDevicesCount(offlineDevicesCount);
devicesInfoVo.setNormalDevicesCount(normalDevicesCount);
devicesInfoVo.setAlarmDevicesCount(alarmDevicesCount);
return devicesInfoVo;
}
/**
* @param: hwDevice
* @param: dbDevice
* @description TdEnginetag
* @author xins
* @date 2023-09-19 10:55
*/
private void updateTdEngine(HwDevice hwDevice, HwDevice dbDevice) {
String deviceType = hwDevice.getDeviceType();
String databaseName = TdEngineConstants.getDatabaseName(hwDevice.getSceneId());
String tableName = TdEngineConstants.getDeviceDataTableName(hwDevice.getDeviceId());
AlterTagVo alterTagVo = new AlterTagVo();
alterTagVo.setDatabaseName(databaseName);
alterTagVo.setTableName(tableName);
R<?> tdReturnMsg;
if (deviceType.equals(HwDictConstants.DEVICE_TYPE_DIRECT_CONNECT_DEVICE)
|| deviceType.equals(HwDictConstants.DEVICE_TYPE_GATEWAY_SUB_EQUIPMENT)) {
if (!hwDevice.getDeviceCode().equals(dbDevice.getDeviceCode())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICECODE);
alterTagVo.setTagValue("'" + hwDevice.getDeviceCode() + "'");
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getDeviceName().equals(dbDevice.getDeviceName())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICENAME);
alterTagVo.setTagValue("'" + hwDevice.getDeviceName() + "'");
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getMonitorUnitId().equals(dbDevice.getMonitorUnitId())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_MONITORUNITID);
alterTagVo.setTagValue(hwDevice.getMonitorUnitId());
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
if (!hwDevice.getDeviceModeId().equals(dbDevice.getDeviceModeId())) {
alterTagVo.setTagName(TdEngineConstants.ST_TAG_DEVICEMODEID);
alterTagVo.setTagValue(hwDevice.getDeviceModeId());
tdReturnMsg = this.remoteTdEngineService.alterTableTag(alterTagVo);
if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常,回滚事务
throw new RuntimeException(tdReturnMsg.getMsg());
}
}
}
}
private Map<Long, Integer> computeDeviceCountPerDay(Long startTime, Long endTime) {
//先增加需要查询的字段名称由于tdengine用last和last_row查询时字段显示有bug所以需要设置要查询的字段
List<TdField> schemaFields = new ArrayList<TdField>();
@ -715,35 +796,4 @@ public class HwDeviceServiceImpl implements IHwDeviceService {
}
}
/**
* @return String
* @param: sceneId
* @description 线
* @author xins
* @date 2023-09-21 9:09
*/
@Override
public JSONObject getOnlineDevicesCount(Long sceneId) {
JSONObject returnObj = new JSONObject();
int onlineDevicesCount = hwDeviceMapper.getOnlineDeviceNum(sceneId);
JSONObject sortedJsonObject = new JSONObject();
String onlineDeviceCountJsonStr = redisTemplate.opsForValue().get(HwDictConstants.REDIS_KEY_ONLINE_DEVICE_COUNT_INFO);
if (onlineDeviceCountJsonStr != null) {
JSONObject jsonObject = JSONObject.parseObject(onlineDeviceCountJsonStr);
jsonObject.forEach((key, value) -> {
String dateStrKey = DateUtils.parseDateToStr(DateUtils.MM_DD, new Date(Long.parseLong(key)));
sortedJsonObject.put(dateStrKey, value);
});
}
returnObj.put("onlineDevicesTrend", sortedJsonObject);
returnObj.put("onlineDevicesCount", onlineDevicesCount);
return returnObj;
}
}

@ -180,6 +180,7 @@ public class HwMonitorUnitServiceImpl implements IHwMonitorUnitService {
@Override
public SubDeviceSumVo selectSubDeviceSum(Long sceneId) {
AllNumsVo numsVo = selectAllNums(sceneId);
//获取在线设备数量,获取已发布状态子设备并且关联网关为在线的数量
int onlineDeviceNum = hwDeviceMapper.getOnlineDeviceNum(sceneId);
SubDeviceSumVo subDeviceSumVo = new SubDeviceSumVo();

@ -76,7 +76,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<!-- 租户数据范围过滤 -->
${params.tenantDataScope}
</where>
order by alarm_info_id desc
order by alarm_info_id desc,hal.level_number desc
</select>
<select id="selectHwAlarmInfoByAlarmInfoId" parameterType="Long" resultMap="HwAlarmInfoResult">
@ -178,4 +178,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where hai.fence_area_id = #{fenceAreaId}
</select>
<select id="selectAlarmCountByMonitorUnitId" parameterType="Long">
SELECT count(distinct(hai.device_id)) FROM hw_alarm_info hai where hai.handle_status='0' and
exists (select 1 from hw_device hd where hai.device_id=hd.device_id and hd.device_status='1'
and hd.monitor_unit_id=#{monitorUnitId})
</select>
</mapper>

@ -229,7 +229,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="getOnlineDeviceNum" parameterType="Long">
SELECT count(1) as count FROM hw_device hd where hd.scene_id=#{sceneId} and hd.device_type=2 and hd.device_status=1
and exists (select 1 from hw_device hdd where hd.releated_device_id=hdd.device_id and hdd.online_status=1)
and exists (select 1 from hw_device hdd where hd.releated_device_id=hdd.device_id and hdd.online_status=1 and hdd.device_status=1)
</select>
<sql id="selectHwDeviceJoinVo">
@ -281,4 +281,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
select count(1) from hw_device where releated_device_id = #{releatedDeviceId} and device_status != '9'
</select>
<select id="selectHwDeviceByDeviceCode" parameterType="String" resultMap="HwDeviceResult">
<include refid="selectHwDeviceVo"/>
where device_code = #{deviceCode} limit 1
</select>
</mapper>

@ -157,7 +157,7 @@
</select>
<!-- 分页查询在impl实现分页-->
<select id="selectLimitSubMonitorUnit" resultMap="HwMonitorUnitResult">
select * from hw_monitor_unit where monitor_unit_id
select * from hw_monitor_unit where monitor_unit_status='1' and monitor_unit_id
not in (select parent_id from hw_monitor_unit where parent_id is not null)
<if test="tenantId != null "> and tenant_id = #{tenantId}</if>
<if test="sceneId != null "> and scene_id = #{sceneId}</if>

@ -70,8 +70,12 @@ public class MqttConfiguration {
String dataTopicFilter;
@Value("${mqtt.client.deviceStatusTopic}")
String deviceStatusTopic;
@Value("${mqtt.client.imagePath}")
@Value("${mqtt.client.path}")
String imagePath;
@Value("${mqtt.client.domain}")
String imageDomain;
@Value("${mqtt.client.prefix}")
String imagePrefix;
@Value("${mqtt.client.imagePatterns}")
String imagePatterns;
@ -129,10 +133,11 @@ public class MqttConfiguration {
logger.info("topic:{} payload:{}", topic, payloadString);
try{
if (topic.startsWith(dataTopicFilter.replace("#","")) && topic.endsWith(TOPIC_TYPE_DATA_POSTFIX)) {
System.out.println("rrrrrr");
dataProcessService.processBusinessData(payloadString, imagePath, imagePatterns);
dataProcessService.processBusinessData(payloadString, imagePath, imagePatterns,imageDomain,imagePrefix);
} else if (topic.equals(deviceStatusTopic)) {
deviceStatusService.handleDeviceStatus(payloadString,clientId);
}else {
dataProcessService.testBase64(payloadString,imagePath,imagePatterns,imageDomain,imagePrefix);
}
}catch(Exception e){
e.printStackTrace();

@ -4,12 +4,17 @@ public interface IDataProcessService {
/**
* @param: jsonData
* @param imagePath
* @param imagePatterns
* @description
* @param: imagePath ruoyifile
* @param: imagePatterns
* @param: imageDomain ruoyifiledomain
* @param: imagePrefix ruoyifileprefix
* @description
* @author xins
* @date 2023-08-31 16:16
*/
public void processBusinessData(String jsonData,String imagePath,String imagePatterns);
public void processBusinessData(String jsonData, String imagePath,
String imagePatterns,String imageDomain,String imagePrefix);
public void testBase64(String jsonData,String imagePath, String imagePatterns,String imageDomain,String imagePrefix);
}

@ -21,6 +21,7 @@ import com.ruoyi.dataprocess.mapper.HwDeviceMapper;
import com.ruoyi.dataprocess.mapper.HwElectronicFenceMapper;
import com.ruoyi.dataprocess.mapper.HwFenceAreaMapper;
import com.ruoyi.dataprocess.service.IDataProcessService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.tdengine.api.RemoteTdEngineService;
import com.ruoyi.tdengine.api.domain.TdField;
import com.ruoyi.tdengine.api.domain.TdTableVo;
@ -30,6 +31,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@ -60,20 +62,22 @@ public class DataProcessServiceImpl implements IDataProcessService {
@Autowired
private HwFenceAreaMapper hwFenceAreaMapper;
@Autowired
private HwAlarmInfoMapper hwAlarmInfoMapper;
/**
* @param imagePath
* @param imagePatterns
* @param: jsonData
* @description
* @param: imagePath ruoyifile
* @param: imagePatterns
* @param: imageDomain ruoyifiledomain
* @param: imagePrefix ruoyifileprefix
* @description
* @author xins
* @date 2023-08-31 16:16
*/
@Override
public void processBusinessData(String jsonData, String imagePath, String imagePatterns) {
public void processBusinessData(String jsonData, String imagePath,
String imagePatterns,String imageDomain,String imagePrefix) {
JSONObject json = JSON.parseObject(jsonData);
Long ts = json.getLong(TdEngineConstants.PAYLOAD_TS);
String tsStr = String.valueOf(ts);
@ -125,14 +129,21 @@ public class DataProcessServiceImpl implements IDataProcessService {
* ,
*/
String[] imagePatternArr = imagePatterns.split(",");
String imageType = ImageUtils.getImageType(valueStr, imagePatternArr);
if (StringUtils.isNotBlank(imageType)) {
String extension = ImageUtils.getImageType(valueStr, imagePatternArr);
if (StringUtils.isNotBlank(extension)) {
//保存图片,并返回图片详细地址进行赋值保存
String imageFileName = ImageUtils.convertBase64ToImage(valueStr, imagePath, imageType, deviceId);
if (StringUtils.isNotBlank(imageFileName)) {
value = imageFileName;
} else {
continue;
String imageFileName = null;
try {
imageFileName = ImageUtils.convertBase64ToImage(imagePath,
valueStr, "device" + deviceId, extension);
if (StringUtils.isNotBlank(imageFileName)) {
value = imageDomain + imagePrefix + imageFileName;
System.out.println(value);
}else {
continue;
}
} catch (IOException e) {
logger.error("转换图片错误:"+e.getMessage(), e);
}
}
@ -242,7 +253,6 @@ public class DataProcessServiceImpl implements IDataProcessService {
circulrVo.setLatitude(Double.valueOf(latitudeStr));
circulrVo.setMarkerType(LocationVo.MARKER_TYPE_CIRCULAR);
boolean isWithin = PositionUtils.checkAddressInLocation(circulrVo, Double.valueOf(String.valueOf(longitude)), Double.valueOf(String.valueOf(latitude)));
System.out.println("iswithin:" + isWithin);
if (triggerStatus.equals(HwDictConstants.ELECTRONIC_FENCE_TRIGGER_STATUS_EXIT) && !isWithin) {//如果电子围栏配置是出界,而此设备出界则报警
isAlarmed = true;
} else if (triggerStatus.equals(HwDictConstants.ELECTRONIC_FENCE_TRIGGER_STATUS_ENTRY) && isWithin) {//如果电子围栏配置是入界,而此设备入界则报警
@ -272,6 +282,38 @@ public class DataProcessServiceImpl implements IDataProcessService {
}
}
@Override
public void testBase64(String jsonData, String imagePath, String imagePatterns, String imageDomain, String imagePrefix) {
JSONObject json = JSON.parseObject(jsonData);
Object value = json.get("base64");
if (value instanceof String) {
String valueStr = (String) value;
if (StringUtils.isNotBlank(valueStr)) {
/**
* ,
*/
String[] imagePatternArr = imagePatterns.split(",");
String extension = ImageUtils.getImageType(valueStr, imagePatternArr);
if (StringUtils.isNotBlank(extension)) {
//保存图片,并返回图片详细地址进行赋值保存
Long deviceId = 100L;
String imageFileName = null;
try {
imageFileName = ImageUtils.convertBase64ToImage(imagePath,
valueStr, "device" + deviceId, extension);
if (StringUtils.isNotBlank(imageFileName)) {
String url = imageDomain + imagePrefix + imageFileName;
System.out.println(url);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

@ -1,9 +1,11 @@
package com.ruoyi.file.controller;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
@ -13,12 +15,11 @@ import com.ruoyi.system.api.domain.SysFile;
/**
*
*
*
* @author ruoyi
*/
@RestController
public class SysFileController
{
public class SysFileController {
private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
@Autowired
@ -28,21 +29,37 @@ public class SysFileController
*
*/
@PostMapping("upload")
public R<SysFile> upload(MultipartFile file)
{
try
{
public R<SysFile> upload(MultipartFile file) {
try {
// 上传并返回访问地址
String url = sysFileService.uploadFile(file);
SysFile sysFile = new SysFile();
sysFile.setName(FileUtils.getName(url));
sysFile.setUrl(url);
return R.ok(sysFile);
} catch (Exception e) {
log.error("上传文件失败", e);
return R.fail(e.getMessage());
}
catch (Exception e)
{
}
/**
* base64
*/
@PostMapping("uploadBase64File")
public R<SysFile> uploadBase64File(@RequestBody Base64FileVo base64FileVo) {
try {
// 上传并返回访问地址
String url = sysFileService.uploadBase64File(base64FileVo);
SysFile sysFile = new SysFile();
sysFile.setName(FileUtils.getName(url));
sysFile.setUrl(url);
return R.ok(sysFile);
} catch (Exception e) {
log.error("上传文件失败", e);
return R.fail(e.getMessage());
}
}
}

@ -2,6 +2,7 @@ package com.ruoyi.file.service;
import java.io.InputStream;
import com.alibaba.nacos.common.utils.IoUtils;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@ -43,4 +44,10 @@ public class FastDfsSysFileServiceImpl implements ISysFileService
IoUtils.closeQuietly(inputStream);
return domain + "/" + storePath.getFullPath();
}
@Override
public String uploadBase64File(Base64FileVo base64FileVo) throws Exception {
return null;
}
}

@ -1,20 +1,29 @@
package com.ruoyi.file.service;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.springframework.web.multipart.MultipartFile;
/**
*
*
*
* @author ruoyi
*/
public interface ISysFileService
{
public interface ISysFileService {
/**
*
*
*
* @param file
* @return 访
* @throws Exception
*/
public String uploadFile(MultipartFile file) throws Exception;
/**
* @return String
* @param: base64FileVo
* @description base64
* @author xins
* @date 2023-10-07 9:22
*/
public String uploadBase64File( Base64FileVo base64FileVo) throws Exception;
}

@ -1,20 +1,20 @@
package com.ruoyi.file.service;
import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.file.utils.FileUploadUtils;
/**
*
*
*
* @author ruoyi
*/
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{
public class LocalSysFileServiceImpl implements ISysFileService {
/**
*
*/
@ -26,7 +26,7 @@ public class LocalSysFileServiceImpl implements ISysFileService
*/
@Value("${file.domain}")
public String domain;
/**
*
*/
@ -35,16 +35,34 @@ public class LocalSysFileServiceImpl implements ISysFileService
/**
*
*
*
* @param file
* @return 访
* @throws Exception
*/
@Override
public String uploadFile(MultipartFile file) throws Exception
{
public String uploadFile(MultipartFile file) throws Exception {
String name = FileUploadUtils.upload(localFilePath, file);
String url = domain + localFilePrefix + name;
return url;
}
/**
* @return String
* @param: base64FileVo
* @description base64
* @author xins
* @date 2023-10-07 9:22
*/
@Override
public String uploadBase64File(Base64FileVo base64FileVo) throws Exception {
String base64Str = base64FileVo.getBase64Str();
String imagePath = base64FileVo.getImagePath();
String extension = base64FileVo.getExtension();
String name = FileUploadUtils.convertBase64ToImage(localFilePath, base64Str, imagePath, extension);
String url = domain + localFilePrefix + name;
return url;
}
}

@ -1,6 +1,8 @@
package com.ruoyi.file.service;
import java.io.InputStream;
import com.ruoyi.system.api.domain.Base64FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@ -46,4 +48,9 @@ public class MinioSysFileServiceImpl implements ISysFileService
IoUtils.closeQuietly(inputStream);
return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
}
@Override
public String uploadBase64File(Base64FileVo base64FileVo) throws Exception {
return null;
}
}

@ -1,9 +1,16 @@
package com.ruoyi.file.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;
import com.ruoyi.common.core.utils.uuid.UUID;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.exception.file.FileException;
@ -18,11 +25,10 @@ import com.ruoyi.common.core.utils.uuid.Seq;
/**
*
*
*
* @author ruoyi
*/
public class FileUploadUtils
{
public class FileUploadUtils {
/**
* 50M
*/
@ -37,22 +43,16 @@ public class FileUploadUtils
*
*
* @param baseDir
* @param file
* @param file
* @return
* @throws IOException
*/
public static final String upload(String baseDir, MultipartFile file) throws IOException
{
try
{
public static final String upload(String baseDir, MultipartFile file) throws IOException {
try {
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
}
catch (FileException fe)
{
} catch (FileException fe) {
throw new IOException(fe.getDefaultMessage(), fe);
}
catch (Exception e)
{
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
@ -60,22 +60,20 @@ public class FileUploadUtils
/**
*
*
* @param baseDir
* @param file
* @param baseDir
* @param file
* @param allowedExtension
* @return
* @throws FileSizeLimitExceededException
* @throws FileSizeLimitExceededException
* @throws FileNameLengthLimitExceededException
* @throws IOException
* @throws InvalidExtensionException
* @throws IOException
* @throws InvalidExtensionException
*/
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
InvalidExtensionException
{
InvalidExtensionException {
int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}
@ -91,28 +89,23 @@ public class FileUploadUtils
/**
*
*/
public static final String extractFilename(MultipartFile file)
{
public static final String extractFilename(MultipartFile file) {
return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), FileTypeUtils.getExtension(file));
}
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
{
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.exists())
{
if (!desc.getParentFile().exists())
{
if (!desc.exists()) {
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
}
return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
}
private static final String getPathFileName(String fileName) throws IOException
{
private static final String getPathFileName(String fileName) throws IOException {
String pathFileName = "/" + fileName;
return pathFileName;
}
@ -122,43 +115,31 @@ public class FileUploadUtils
*
* @param file
* @throws FileSizeLimitExceededException
* @throws InvalidExtensionException
* @throws InvalidExtensionException
*/
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
throws FileSizeLimitExceededException, InvalidExtensionException
{
throws FileSizeLimitExceededException, InvalidExtensionException {
long size = file.getSize();
if (size > DEFAULT_MAX_SIZE)
{
if (size > DEFAULT_MAX_SIZE) {
throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
}
String fileName = file.getOriginalFilename();
String extension = FileTypeUtils.getExtension(file);
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
{
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
{
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
{
} else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
{
} else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
{
} else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) {
throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
fileName);
}
else
{
} else {
throw new InvalidExtensionException(allowedExtension, extension, fileName);
}
}
@ -167,19 +148,61 @@ public class FileUploadUtils
/**
* MIMEMIME
*
* @param extension
* @param extension
* @param allowedExtension
* @return true/false
*/
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
{
for (String str : allowedExtension)
{
if (str.equalsIgnoreCase(extension))
{
public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
for (String str : allowedExtension) {
if (str.equalsIgnoreCase(extension)) {
return true;
}
}
return false;
}
public static final String extractFilename(String originalFileName, String imagePath, String extension) {
return StringUtils.format("{}/{}/{}_{}.{}", imagePath, DateUtils.datePath(),
FilenameUtils.getBaseName(originalFileName), Seq.getId(Seq.uploadSeqType), extension);
}
/**
* @param: base64
* @param: imageFileName
* @description base64
* @author xins
* @date 2023-09-04 15:59
*/
public static String convertBase64ToImage(String baseDir, String base64Str, String imagePath, String extension) throws IOException {
// 解密
try {
String originalFileName = UUID.randomUUID().toString();
String fileName = extractFilename(originalFileName, imagePath, extension);
String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
// 去掉base64前缀 data:image/jpeg;base64,
base64Str = base64Str.substring(base64Str.indexOf(",", 1) + 1);
// 解密解密的结果是一个byte数组
Base64.Decoder decoder = Base64.getDecoder();
byte[] imgbytes = decoder.decode(base64Str);
for (int i = 0; i < imgbytes.length; ++i) {
if (imgbytes[i] < 0) {
imgbytes[i] += 256;
}
}
// 保存图片
OutputStream out = new FileOutputStream(absPath);
out.write(imgbytes);
out.flush();
out.close();
// 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
return getPathFileName(fileName);
} catch (IOException e) {
throw new IOException(e.getMessage(), e);
}
}
}

@ -18,14 +18,12 @@ import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
@SpringBootApplication
public class RuoYiSystemApplication
{
@Value("${spring.nacos.config.server-addr}")
public static String dd;
// @Value("${spring.nacos.config.server-addr}")
// public static String dd;
public static void main(String[] args)
{
System.out.println("---"+dd);
SpringApplication.run(RuoYiSystemApplication.class, args);
System.out.println("-----"+dd);
System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +
" | _ _ \\ \\ \\ / / \n" +

@ -92,6 +92,8 @@ public class SysRoleController extends BaseController
{
return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setTenantId(SecurityUtils.getTenantId());
role.setCreateBy(SecurityUtils.getUsername());
return toAjax(roleService.insertRole(role));

@ -48,7 +48,7 @@ public class SysRoleServiceImpl implements ISysRoleService {
* @return
*/
@Override
@DataScope(deptAlias = "d")
@DataScope(deptAlias = "d",tenantAlias = "r")
public List<SysRole> selectRoleList(SysRole role) {
return roleMapper.selectRoleList(role);
}

@ -57,6 +57,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
<!-- 数据范围过滤 -->
${params.dataScope}
<!-- 租户数据范围过滤 -->
${params.tenantDataScope}
order by r.role_sort
</select>
@ -109,6 +111,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="status != null and status != ''">status,</if>
<if test="remark != null and remark != ''">remark,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
<if test="tenantId != null and tenantId != 0">tenant_id,</if>
create_time
)values(
<if test="roleId != null and roleId != 0">#{roleId},</if>
@ -121,6 +124,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="status != null and status != ''">#{status},</if>
<if test="remark != null and remark != ''">#{remark},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
<if test="tenantId != null and tenantId != 0">#{tenantId},</if>
sysdate()
)
</insert>

@ -152,15 +152,15 @@
<dict-tag :options="dict.type.hw_device_online_status" :value="scope.row.onlineStatus"/>
</template>
</el-table-column-->
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-table-column label="设备控制" align="center" class-name="small-padding fixed-width" >
<template slot-scope="scope" v-if="scope.row.deviceType=='1' || scope.row.deviceType=='3'">
<el-button
size="mini"
type="text"
icon="el-icon-time"
@click="publishControlCommand(scope.row,'CMD_SYS_TIME_CHECK','设备对时')"
v-hasPermi="['business:device:edit']"
>设备对
>
</el-button>
<el-button
size="mini"
@ -174,14 +174,26 @@
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
icon="el-icon-refresh-right"
@click="publishControlCommand(scope.row,'CMD_SYS_REBOOT','重启')"
v-hasPermi="['business:device:edit']"
>修改
>重启
</el-button>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
v-hasPermi="['business:device:edit']"
>修改
</el-button>
<el-button
size="mini"
@ -907,10 +919,10 @@ export default {
},
publishControlCommand(row,type,typeName){
this.$modal.confirm('确认要进行'+typeName+'么?').then(function () {
this.$modal.confirm('确认要下发指令'+typeName+'么?').then(function () {
return publishControlCommand(row.deviceId, type);
}).then(() => {
this.$modal.msgSuccess("执行成功");
this.$modal.msgSuccess("下发指令成功");
})
}

Loading…
Cancel
Save