package com.sandu.ximon.admin.service; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import com.aliyuncs.iot.model.v20180120.BatchGetDeviceStateResponse; import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.github.pagehelper.PageHelper; import com.sandu.common.execption.BusinessException; import com.sandu.common.redis.RedisService; import com.sandu.common.service.impl.BaseServiceImpl; import com.sandu.ximon.admin.dto.DeviceStatus; import com.sandu.ximon.admin.manager.iot.frame.A1Frame; import com.sandu.ximon.admin.manager.iot.frame.FrameBuilder; import com.sandu.ximon.admin.manager.iot.frame.IRequestFrame; import com.sandu.ximon.admin.manager.iot.frame.inner.request.A1TernaryCodeReqInnerFrame; import com.sandu.ximon.admin.manager.iot.frame.inner.request.A5LightResetReqInnerFrame; import com.sandu.ximon.admin.manager.iot.frame.inner.request.EmptyRequestInnerFrame; import com.sandu.ximon.admin.manager.iot.frame.inner.response.A1DeviceMacRespInnerFrame; import com.sandu.ximon.admin.manager.iot.frame.inner.response.A1TernaryCodeRespInnerFrame; import com.sandu.ximon.admin.manager.iot.rrpc.dto.CommonFrame; import com.sandu.ximon.admin.manager.iot.rrpc.dto.WrapResponseCommonFrame; import com.sandu.ximon.admin.manager.iot.rrpc.enums.A1OrderEnum; import com.sandu.ximon.admin.manager.iot.rrpc.enums.A2OrderEnum; import com.sandu.ximon.admin.manager.iot.rrpc.enums.A5OrderEnum; import com.sandu.ximon.admin.manager.iot.rrpc.enums.DeviceStateEnum; import com.sandu.ximon.admin.manager.iot.rrpc.mainboard.MainBoardInvokeSyncService; import com.sandu.ximon.admin.param.PoleBindingParam; import com.sandu.ximon.admin.param.PoleParam; import com.sandu.ximon.admin.param.PoleStatesParam; import com.sandu.ximon.admin.redis.LightKey; import com.sandu.ximon.admin.security.SecurityUtils; import com.sandu.ximon.dao.domain.Pole; import com.sandu.ximon.dao.domain.PoleBinding; import com.sandu.ximon.dao.domain.PoleGroupRelation; import com.sandu.ximon.dao.mapper.PoleMapper; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * 灯杆相关 * * @author chenjiantian */ @Service @Slf4j @AllArgsConstructor public class PoleService extends BaseServiceImpl { private final RedisService redisService; private final PoleBindingService poleBindingService; private final PoleGroupRelationService groupRelationService; public boolean addPole(PoleParam param) { Pole pole = new Pole(); BeanUtils.copyProperties(param, pole); pole.setPoleCode(generatePoleCode()); return save(pole); } public boolean updatePole(Long poleId, PoleParam param) { Pole pole = getById(poleId); if (pole == null) { throw new BusinessException("未找到该灯杆"); } Pole update = new Pole(); BeanUtils.copyProperties(param, update); update.setId(poleId); return updateById(update); } /** * 删除灯杆 */ public boolean deletePole(Long poleId) { Pole pole = getById(poleId); if (pole == null) { throw new BusinessException("未找到该灯杆"); } return removeById(poleId); } /** * 生成灯杆编号 */ public Long generatePoleCode() { StringBuilder sb = new StringBuilder(); String date = new SimpleDateFormat("yyMMdd").format(new Date()); sb.append(date); String key = LightKey.POLE_SN.key(null); Long increment = redisService.incr(key, 1); String incrementStr = increment.toString(); if (incrementStr.length() <= 4) { sb.append(String.format("%04d", increment)); } else { sb.append(incrementStr); } return Long.parseLong(sb.toString()); } public List queryAllStatesAndList(Integer pageNo, Integer pageSize, PoleStatesParam param) { // List list = list(Wrappers.lambdaQuery(LampPost.class).eq(LampPost::getClientId, SecurityUtils.getUserId())); //List list = list(Wrappers.lambdaQuery(Pole.class)); // PageHelper.startPage(pageNo, pageSize); List list = new ArrayList<>(); LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); if (SecurityUtils.getClientId() == null) { wrapper = Wrappers.lambdaQuery(Pole.class); } else { wrapper = Wrappers.lambdaQuery(Pole.class).eq(Pole::getClientId, SecurityUtils.getUserId()); } if (!param.getKeyword().isEmpty()) { wrapper.like(Pole::getPoleCode, param.getKeyword()).or( wrappers -> { wrappers.like(Pole::getPoleName, param.getKeyword()); } ); } list = list(wrapper); List bindList = new ArrayList<>();//已绑定客户 List unbindList = new ArrayList<>();//未绑定客户 List isTrue = new ArrayList<>();//实体灯杆 List isFalse = new ArrayList<>();//虚拟灯杆 List online = new ArrayList<>();//在线 List offline = new ArrayList<>();//离线 if (param.getGroupid() != null) { // List poleIds = new ArrayList<>(); List pole = new ArrayList<>(); List relations = groupRelationService.list(Wrappers.lambdaQuery(PoleGroupRelation.class) .eq(PoleGroupRelation::getPoleGroupId, param.getGroupid())); relations.forEach(relation -> { pole.add(getById(relation.getPoleId())); } ); list = pole; } list.forEach(bindwarpper -> { // Long clientId = bindwarpper.getClientId(); if (bindwarpper.getClientId() == null) {//判断是否绑定 unbindList.add(bindwarpper); if (bindwarpper.getDeviceCode() == null) {//判断灯杆类型 isFalse.add(bindwarpper); } else { isTrue.add(bindwarpper); } } else { bindList.add(bindwarpper); if (bindwarpper.getDeviceCode() == null) { isFalse.add(bindwarpper); } else { isTrue.add(bindwarpper); } } }); if (param.getBingStates() == 1) { //未绑定 list = unbindList; } else if (param.getBingStates() == 0) {//已绑定 list = bindList; }// else {//全部 // list = list(wrapper); // } setOnline(list); if (param.getIsTrue() == 1) { //虚拟灯杆 list = isFalse; } else if (param.getIsTrue() == 0) {//实体灯杆 list = isTrue; list.forEach(onLinePole -> { // System.out.println("online-----------------------"+onLinePole.getOnLineState()); if (("ONLINAE").equals(onLinePole.getOnLineState())) { online.add(onLinePole); } else if (("OFFLINE").equals(onLinePole.getOnLineState())) { offline.add(onLinePole); } }); } else {//全部 // setOnline(list); list.forEach(onLinePole -> { // System.out.println("online-----------------------"+onLinePole.getOnLineState()); if (("ONLINE").equals(onLinePole.getOnLineState())) { online.add(onLinePole); } else if (("OFFLINE").equals(onLinePole.getOnLineState())) { offline.add(onLinePole); } }); } if (param.getOnLineStates() == 1) { //离线 list = offline; } else if (param.getOnLineStates() == 0) {//在线 list = online; } setCount(list); return list; } /** * 设置绑定设备数量 * @param list * @return */ public List setCount(List list) { for (Pole post : list) { int size = poleBindingService.list(Wrappers.lambdaQuery(PoleBinding.class).eq(PoleBinding::getPoleId, post.getId())).size(); // System.out.println("size:----------------------"+size); post.setBindingCount(size); } return list; } /** * 设置在线状态 * @param list * @return */ public List setOnline(List list) { List MacCodes = new ArrayList<>(); for (Pole post : list) { if (post.getDeviceCode() != null) { MacCodes.add(post.getDeviceCode()); } } // List deviceStatuses = MainBoardInvokeSyncService.getInstance().batchGetDeviceState(MacCodes); if (deviceStatuses != null) { for (Pole post : list) { for (BatchGetDeviceStateResponse.DeviceStatus deviceStatus : deviceStatuses) { // System.out.println("DeviceCode:---------------------"+post.getDeviceCode()); // System.out.println("DeviceName:---------------------"+deviceStatus.getDeviceName()); if (post.getDeviceCode() != null && post.getDeviceCode().equals(deviceStatus.getDeviceName())) { post.setOnLineState(deviceStatus.getStatus()); // int size = poleBindingService.list(Wrappers.lambdaQuery(PoleBinding.class).eq(PoleBinding::getPoleId, post.getId())).size(); //// System.out.println("size:----------------------"+size); // post.setBindingCount(size); } } // MacCodes.add(post.getDeviceCode()); } } return list; } /** * 查询灯杆的在线状态并赋值 * * @return */ public List queryStatesAndList(Integer pageNo, Integer pageSize, String keyword, Long groupid) { // List list = list(Wrappers.lambdaQuery(LampPost.class).eq(LampPost::getClientId, SecurityUtils.getUserId())); //List list = list(Wrappers.lambdaQuery(Pole.class)); PageHelper.startPage(pageNo, pageSize); List list = new ArrayList<>(); LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); if (SecurityUtils.getClientId() == null) { wrapper = Wrappers.lambdaQuery(Pole.class); } else { wrapper = Wrappers.lambdaQuery(Pole.class).eq(Pole::getClientId, SecurityUtils.getUserId()); } if (!keyword.isEmpty()) { wrapper.like(Pole::getPoleCode, keyword).or( wrappers -> { wrappers.like(Pole::getPoleName, keyword); } ); } list = list(wrapper); List MacCodes = new ArrayList<>(); for (Pole post : list) { MacCodes.add(post.getDeviceCode()); } List deviceStatuses = MainBoardInvokeSyncService.getInstance().batchGetDeviceState(MacCodes); for (Pole post : list) { for (BatchGetDeviceStateResponse.DeviceStatus deviceStatus : deviceStatuses) { // System.out.println("DeviceCode:---------------------"+post.getDeviceCode()); // System.out.println("DeviceName:---------------------"+deviceStatus.getDeviceName()); if (post.getDeviceCode() != null && post.getDeviceCode().equals(deviceStatus.getDeviceName())) { post.setOnLineState(deviceStatus.getStatus()); int size = poleBindingService.list(Wrappers.lambdaQuery(PoleBinding.class).eq(PoleBinding::getPoleId, post.getId())).size(); // System.out.println("size:----------------------"+size); post.setBindingCount(size); } } // MacCodes.add(post.getDeviceCode()); } return list; } /** * 灯杆绑定设备 * * @param poleId 绑定灯杆id * @param param 被绑定设备信息 * @return 是否成功 */ public boolean bindPole(Long poleId, PoleBindingParam param) { Pole pole = getById(poleId); if (pole == null) { throw new BusinessException("未找到该灯杆"); } return poleBindingService.bindPole(poleId, param); } /** * 灯杆解绑绑定设备 * * @return 是否成功 */ public boolean unBindPole(String deviceCode) { return poleBindingService.unBindPole(deviceCode); } /** * 灯杆恢复出厂设置 * * @param id * @return */ public boolean poleReset(Long id) { Pole byId = getById(id); String deviceName = byId.getDeviceCode(); if (byId == null) { throw new BusinessException("未找到该灯杆"); } if (deviceName.isEmpty()) { throw new BusinessException("该灯杆Mca为空"); } IRequestFrame build = FrameBuilder.builderA5() .orderType(A5OrderEnum.REQUEST_LIGHT_DATA.getCode()) .innerFrame(new A5LightResetReqInnerFrame()) .build(); CommonFrame commonFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(deviceName, build); System.out.println(commonFrame.toString()); CommonFrame rebootFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(deviceName, FrameBuilder.builderA2().innerFrame(new EmptyRequestInnerFrame()) .orderType(A2OrderEnum.REQUEST_MAIN_BOARD_RESET.getCode()).build()); if ("00".equals(rebootFrame.getPayload())) { System.out.println("重启成功"); } CommonFrame result = MainBoardInvokeSyncService.getInstance() .sendRRPC(deviceName, FrameBuilder.builderA2().innerFrame(new EmptyRequestInnerFrame()) .orderType(A2OrderEnum.REQUEST_MAIN_BOARD_RESET.getCode()).build()); boolean b = false; if ("00".equals(result.getPayload())) { byId.setDeviceCode(null); b = updateById(byId); System.out.println("重启成功"); } return b; } /** * 给灯杆注册三元码 */ public boolean setMac(String baseMac) { // public boolean setMac() { //Pole pole = getById(poleId); /* if (pole == null) { throw new BusinessException("未找到该灯杆"); }*/ boolean setMac = false; //String baseMac = "baseDevice"; A1Frame a1Frame = new A1Frame(A1OrderEnum.REQUEST_READ_DEVICE_UNIQUE_MAC.getCode(), new EmptyRequestInnerFrame()); CommonFrame commonFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(baseMac, a1Frame); if (commonFrame == null) { throw new BusinessException("读取设备唯一ID失败"); } A1DeviceMacRespInnerFrame a1DeviceMacRespInnerFrame = new A1DeviceMacRespInnerFrame().transformFrame(commonFrame.getPayload()); log.info(commonFrame.toString()); String uniqueMac = a1DeviceMacRespInnerFrame.getMac(); uniqueMac = uniqueMac.toLowerCase(); if (uniqueMac.isEmpty()) { throw new BusinessException("读取设备唯一ID失败!"); } log.info("唯一码{}", uniqueMac); // 2 从阿里注册 MainBoardInvokeSyncService.getInstance().registerDevice(uniqueMac); // 3 获取设备详情 QueryDeviceDetailResponse.Data deviceDetail = MainBoardInvokeSyncService.getInstance().queryDeviceDetail(uniqueMac, null); if (deviceDetail == null) { throw new BusinessException("注册失败"); } log.info(deviceDetail.toString()); // 4 配置Mac① WrapResponseCommonFrame productKeyResp = MainBoardInvokeSyncService.getInstance() .sendRRPC(baseMac, FrameBuilder.builderA1().innerFrame(new A1TernaryCodeReqInnerFrame(MainBoardInvokeSyncService.getInstance().getProductKey())) .orderType(A1OrderEnum.REQUEST_SET_PRODUCT_KEY.getCode()).build(), A1TernaryCodeRespInnerFrame.class); A1TernaryCodeRespInnerFrame responseInnerFrame = productKeyResp.getResponseInnerFrame(); if (!MainBoardInvokeSyncService.getInstance().getProductKey().equals(responseInnerFrame.getTernaryCode())) { throw new BusinessException("设备配置ProductKey失败"); } // 5 配置Mac② WrapResponseCommonFrame responseCommonFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(baseMac, FrameBuilder.builderA1().innerFrame(new A1TernaryCodeReqInnerFrame(uniqueMac)) .orderType(A1OrderEnum.REQUEST_SET_DEVICE_NAME.getCode()).build(), A1TernaryCodeRespInnerFrame.class); A1TernaryCodeRespInnerFrame deviceNameFrame = responseCommonFrame.getResponseInnerFrame(); if (!uniqueMac.equals(deviceNameFrame.getTernaryCode())) { throw new BusinessException("设备配置名失败"); } // 6 配置Mac③ WrapResponseCommonFrame wrapResponseCommonFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(baseMac, FrameBuilder.builderA1().innerFrame(new A1TernaryCodeReqInnerFrame(deviceDetail.getDeviceSecret())) .orderType(A1OrderEnum.REQUEST_SET_DEVICE_SECRET.getCode()).build(), A1TernaryCodeRespInnerFrame.class); A1TernaryCodeRespInnerFrame deviceSecretFrame = wrapResponseCommonFrame.getResponseInnerFrame(); if (!deviceDetail.getDeviceSecret().equals(deviceSecretFrame.getTernaryCode())) { throw new BusinessException("设备密钥失败"); } // 7 重启设备 并使用新的Mac CommonFrame rebootFrame = MainBoardInvokeSyncService.getInstance() .sendRRPC(baseMac, FrameBuilder.builderA2().innerFrame(new EmptyRequestInnerFrame()) .orderType(A2OrderEnum.REQUEST_MAIN_BOARD_RESET.getCode()).build()); if ("00".equals(rebootFrame.getPayload())) { // pole.setDeviceCode(uniqueMac); // setMac = updateById(pole); System.out.println("重启成功"); } Pole pole = new Pole(); String strh = uniqueMac.substring(uniqueMac.length() - 2, uniqueMac.length()); pole.setDeviceCode(strh); pole.setPoleName(strh); String strm = uniqueMac.substring(0, uniqueMac.length() - 2); int i = Integer.parseInt(strm); pole.setPoleCode(generatePoleCode()); pole.setDeviceType(i); setMac = save(pole); return setMac; } public List listDeviceCodeByIds(List poleIdList) { if (CollectionUtil.isEmpty(poleIdList)) { return null; } List list = list(Wrappers.lambdaQuery(Pole.class).in(Pole::getId, poleIdList).select(Pole::getDeviceCode)); return list .stream().filter(Objects::nonNull).map(Pole::getDeviceCode).filter(StrUtil::isNotEmpty).collect(Collectors.toList()); } /** * 批量获取阿里云设备的状态 * * @param deviceCodeList 阿里云设备码 * @return 设备状态列表 */ public List listStatusByDeviceCode(ArrayList deviceCodeList) { // 最大只能查50个 List> split = CollectionUtil.split(deviceCodeList, 50); List statusList = new ArrayList<>(); for (List list : split) { List deviceStatuses = MainBoardInvokeSyncService.getInstance().batchGetDeviceState(list); if (CollectionUtil.isNotEmpty(deviceStatuses)) { for (BatchGetDeviceStateResponse.DeviceStatus d : deviceStatuses) { DeviceStatus deviceStatus = new DeviceStatus(); deviceStatus.setDeviceCode(d.getDeviceName()); deviceStatus.setStatus(DeviceStateEnum.getCode(d.getStatus())); statusList.add(deviceStatus); } } } return statusList; } /** * 用户绑定灯杆 * * @param clientId 用户ID * @param poleIds 灯杆ID * @return */ public boolean ClientBindingPole(long clientId, int[] poleIds) { boolean r = false; for (int poleId : poleIds) { Pole pole = getById(poleId); if (pole == null) { throw new BusinessException("灯杆不存在"); } pole.setClientId(clientId); r = updateById(pole); if (!r) { throw new BusinessException("灯杆ID为" + poleId + "设置失败,自动停止"); } } return r; } }