package com.maibu.init; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.Executor; import java.util.stream.Collectors; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.maibu.constant.FastBeeConstant; import com.maibu.core.business.AlarmOrderConfig; import com.maibu.core.business.DeviceModel; import com.maibu.core.business.DevicePlan; import com.maibu.core.business.DevicePlanTask; import com.maibu.core.business.DeviceRunParam; import com.maibu.core.business.ErrorIdentificationStandard; import com.maibu.core.business.IoTCommonDevice; import com.maibu.core.business.OrderModel; import com.maibu.core.business.Product; import com.maibu.core.business.WorkRecord; import com.maibu.core.domain.entity.SysParam; import com.maibu.core.domain.entity.SysSite; import com.maibu.core.domain.map.SiteMapInfo; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.core.enums.RouteType; import com.maibu.influxdb.util.InfluxDBUtil; import com.maibu.mapper.AlarmOrderConfigMapper; import com.maibu.mapper.DevicePlanMapper; import com.maibu.mapper.DevicePlanTaskMapper; import com.maibu.mapper.DeviceProductMapper; import com.maibu.mapper.DeviceRunParamMapper; import com.maibu.mapper.ErrorIdentificationStandardMapper; import com.maibu.mapper.IotDeviceCommonMapper; import com.maibu.mapper.OrderModelMapper; import com.maibu.mapper.SiteMapInfoMapper; import com.maibu.mapper.SysDeviceModelMapper; import com.maibu.mapper.SysParamMapper; import com.maibu.mapper.SysSiteMapper; import com.maibu.mapper.WorkRecordMapper; import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; import com.maibu.mybatis.LambdaQueryWrapperX; import com.maibu.service.DevicePlanTaskMonitorService; import com.maibu.service.DeviceThreadService; import com.maibu.service.impl.IotDeviceCommonService; import cn.hutool.core.io.IoUtil; import lombok.extern.slf4j.Slf4j; @Slf4j @Component @Order(20) public class InitThread implements ApplicationRunner { @Resource(name = FastBeeConstant.TASK.DEVICE_ERROR_MONITOR) private Executor deviceErrorMonitorExecutor; @Resource(name = FastBeeConstant.TASK.DEVICE_HEARTBEAT_MONITOR) private Executor deviceHeartBeatMonitorExecutor; @Resource(name = FastBeeConstant.TASK.MAP_MESSAGE_PUSH) private Executor mapMessagePushExecutor; @Resource(name = FastBeeConstant.TASK.AUTO_RULE) private Executor autoRuleExecutor; @Resource(name = FastBeeConstant.TASK.COMMON_DEVICE_MONITOR) private Executor commonDeviceMonitorExecutor; @Resource(name = FastBeeConstant.TASK.DEVICE_TASK_HANDLER) private Executor deviceTaskHandlerExecutor; @Autowired private DeviceThreadService deviceThreadService; @Autowired private DevicePlanTaskMonitorService devicePlanTaskMonitorService; @Autowired private DevicePlanMapper devicePlanMapper; @Autowired private DevicePlanTaskMapper devicePlanTaskMapper; @Autowired private SysSiteMapper sysSiteMapper; @Autowired private SiteMapInfoMapper siteMapInfoMapper; @Autowired private DeviceRunParamMapper deviceRunParamMapper; @Autowired private IotDeviceCommonMapper iotDeviceCommonMapper; @Autowired private DeviceProductMapper deviceProductMapper; @Autowired private SysDeviceModelMapper deviceModelMapper; @Autowired private ErrorIdentificationStandardMapper errorIdentificationStandardMapper; @Autowired private OrderModelMapper orderModelMapper; @Autowired private AlarmOrderConfigMapper alarmOrderConfigMapper; @Autowired private IotDeviceCommonService commonService; @Autowired private ResourceLoader resourceLoader; @Autowired private SysParamMapper sysParamMapper; @Autowired private WorkRecordMapper workRecordMapper; @Value("${influxdb.url}") private String influxDBUrl; @Value("${influxdb.username}") private String influxDBUsername; @Value("${influxdb.password}") private String influxDBPassword; @Value("${influxdb.bucket}") private String influxDBBucket; @Value("${influxdb.org}") private String influxDBOrg; @Value("${influxdb.token}") private String influxDBToken; @Value("${mqtt.username}") private String mqttUsername; @Value("${mqtt.password}") private String mqttPassword; @Value("${mqtt.host-url}") private String mqttHostUrl; @Value("${mqtt.client-id}") private String mqttClientId; @Override public void run(ApplicationArguments args) throws Exception { recoverMemory(); init(); } private void init() throws Exception { // 初始化系统参数 initSystemParam(); initDefaultWorkRecord(); // 初始化InfluxDBUtil GlobalMemory.influxDBUtil = new InfluxDBUtil(influxDBUrl, influxDBToken, influxDBOrg, influxDBBucket); GlobalMemory.initMqttDeviceMonitor(mqttHostUrl, mqttClientId, mqttUsername, mqttPassword); // 规则触发线程 autoRuleExecutor.execute(() -> { deviceThreadService.autoRule(); }); // 地图监控推送 mapMessagePushExecutor.execute(() -> { deviceThreadService.mapMessagePush(); }); // 上位机设备心跳监控 deviceHeartBeatMonitorExecutor.execute(() -> { deviceThreadService.heartBeatMonitor(); }); // 设备错误监听线程 deviceErrorMonitorExecutor.execute(() -> { try { deviceThreadService.deviceErrorMonitor(); } catch (InterruptedException | IOException e) { throw new RuntimeException(e); } }); // 设备任务处理线程 deviceTaskHandlerExecutor.execute(() -> { // 任务下发 try { devicePlanTaskMonitorService.generatePlanTask(); // 执行准备队列 devicePlanTaskMonitorService.doLoop(); // 执行任务 devicePlanTaskMonitorService.doExecute(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); commonDeviceMonitorExecutor.execute(() -> { commonService.commonDeviceMonitor(); }); } /** * 恢复内存 */ public void recoverMemory() { List siteList = sysSiteMapper.selectList(); if (!CollectionUtils.isEmpty(siteList)) { siteList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory == null) { siteMemory = new SiteMemory(); siteMemory.setSiteId(siteId); siteMemory.setSysSite(x); GlobalMemory.addSiteMemory(orgId, siteId, siteMemory); } }); } // 场站的 地图配置信息 List siteMapInfoList = siteMapInfoMapper.selectList(); if (!CollectionUtils.isEmpty(siteMapInfoList)) { siteMapInfoList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.getSysSite().setSiteMapInfo(x); } }); } // 外部设备 List ioTCommonDeviceList = iotDeviceCommonMapper.selectList(); if (!CollectionUtils.isEmpty(ioTCommonDeviceList)) { ioTCommonDeviceList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveCommonDevice(x); } }); } // 产品 List productList = deviceProductMapper.selectList(); if (!CollectionUtils.isEmpty(productList)) { productList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveProduct(x); } }); } // 设备模型 List deviceModelList = deviceModelMapper.selectList(); if (!CollectionUtils.isEmpty(deviceModelList)) { deviceModelList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveDeviceModel(x); } }); } // 车辆参数 List deviceRunParamList = deviceRunParamMapper.selectList(); if (!CollectionUtils.isEmpty(deviceRunParamList)) { deviceRunParamList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveDeviceRunParam(x); } }); } // 错误标准 List standadList = errorIdentificationStandardMapper.selectList(); if (!CollectionUtils.isEmpty(standadList)) { standadList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveErrorIdentificationStandard(x); } }); } // 订单模型 List orderModelList = orderModelMapper.selectList(); if (!CollectionUtils.isEmpty(orderModelList)) { orderModelList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveOrderModel(x); } }); } // 告警订单配置 List alarmOrderList = alarmOrderConfigMapper.selectList(); if (!CollectionUtils.isEmpty(alarmOrderList)) { alarmOrderList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.saveAlarmOrderConfig(x); } }); } // 未执行完的重复计划 LambdaQueryWrapperX query = new LambdaQueryWrapperX<>(); List list = Arrays.asList(DeviceTaskStaus.NEW.getCode(), DeviceTaskStaus.EXECUTING.getCode(), DeviceTaskStaus.PAUSE.getCode()); query.in(DevicePlan::getTaskStaus, list); List devicePlanList = devicePlanMapper.selectList(query); if (!CollectionUtils.isEmpty(devicePlanList)) { devicePlanList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.addDevicePlan(x); } }); } // 未执行完的重复计划 LambdaQueryWrapperX taskQuery = new LambdaQueryWrapperX<>(); taskQuery.eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.NEW.getCode()); List newStatusList = devicePlanTaskMapper.selectList(taskQuery); if (!CollectionUtils.isEmpty(newStatusList)) { newStatusList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.addDevicePlanPrepare(x); } }); } LambdaQueryWrapperX executeTaskQuery = new LambdaQueryWrapperX<>(); executeTaskQuery.eq(DevicePlanTask::getTaskStaus, DeviceTaskStaus.EXECUTING.getCode()); List executeStatusList = devicePlanTaskMapper.selectList(executeTaskQuery); if (!CollectionUtils.isEmpty(executeStatusList)) { executeStatusList.forEach(x -> { Long orgId = x.getOrgId(); Long siteId = x.getSiteId(); SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { siteMemory.addDevicePlanExecute(x); } }); } } public void initSystemParam() throws IOException { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); List list = sysParamMapper.selectList(queryWrapper); try { // 读取resource目录下的dsystemParam.json文件 org.springframework.core.io.Resource resource = resourceLoader .getResource("classpath:systemParam.json"); // 使用fastjson2转换为DeviceConfig对象 String jsonContent; jsonContent = IoUtil.readUtf8(resource.getInputStream()); List params = JSON.parseArray(jsonContent, SysParam.class); List saveList = new ArrayList<>(); if (CollectionUtils.isEmpty(list)) { saveList.addAll(params); } else { Map map = list.stream() .collect(Collectors.toMap( SysParam::getParamKey, sysParam -> sysParam)); if (!CollectionUtils.isEmpty(params)) { params.forEach(x -> { if (!map.containsKey(x.getParamKey())) { saveList.add(x); } }); } } sysParamMapper.saveOrUpdateBatch(saveList); } catch (Exception e) { log.error("初始化系统参数失败", e); } } public void initDefaultWorkRecord() throws IOException { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); List list = workRecordMapper.selectList(queryWrapper); try { // 读取resource目录下的dsystemParam.json文件 org.springframework.core.io.Resource resource = resourceLoader .getResource("classpath:workRecordTemplete.json"); // 使用fastjson2转换为DeviceConfig对象 String jsonContent; jsonContent = IoUtil.readUtf8(resource.getInputStream()); List records = JSON.parseArray(jsonContent, WorkRecord.class); List saveList = new ArrayList<>(); if (CollectionUtils.isEmpty(list)) { saveList.addAll(records); } else { Map> map = list.stream() .filter(Objects::nonNull) .filter(workRecord -> workRecord.getRouteType() != null) .collect(Collectors.groupingBy( workRecord -> workRecord.getRouteType().toString())); if (!CollectionUtils.isEmpty(records)) { records.forEach(x -> { if (!map.containsKey(x.getRouteType())) { x.setUserId(1L); saveList.add(x); } }); } } workRecordMapper.saveOrUpdateBatch(saveList); } catch (Exception e) { log.error("初始化系统参数失败", e); } } }