diff --git a/maibu-admin/src/main/resources/application-dev.yml b/maibu-admin/src/main/resources/application-dev.yml index 0d6d5d7..76a1d2c 100644 --- a/maibu-admin/src/main/resources/application-dev.yml +++ b/maibu-admin/src/main/resources/application-dev.yml @@ -87,3 +87,10 @@ influxdb: minio: endpoint : https://oss.satabot.com + + +agora: + appId : 5afc6f096ddf433aa690df6f251274a4 + appCertificate : ce6a402337554fa9a1f690f721cf0053 + tokenExpirationInSeconds : 3600 + privilegeExpirationInSeconds : 3600 diff --git a/maibu-common/src/main/java/com/maibu/constant/Constant.java b/maibu-common/src/main/java/com/maibu/constant/Constant.java index aab0da4..4c48343 100644 --- a/maibu-common/src/main/java/com/maibu/constant/Constant.java +++ b/maibu-common/src/main/java/com/maibu/constant/Constant.java @@ -32,5 +32,5 @@ public class Constant { // ==================== 远程控制 ==================== public static final String protocol_version = "1.4.7"; public static final String remote_control_msg_prefix = "remote-msg"; - public static final String remote_control_cmd_prefix = "remote-cmd"; + public static final String remote_control_cmd_prefix = "remote-cmd_"; } diff --git a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java index 1bb219f..020fb86 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java @@ -70,4 +70,7 @@ public class DevicePlanTask extends OrgBaseDO { private String failedReason; + + private String canceledReason; + } diff --git a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java index 989f283..b959f32 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java +++ b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java @@ -9,10 +9,12 @@ import com.maibu.core.business.path.RoutePlanSendEntity; import com.maibu.core.enums.ConnectorType; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.core.enums.RouteType; +import com.maibu.core.host.DeviceRemoteControlDTO; import com.maibu.core.host.HostEstopChangeDTO; import com.maibu.core.host.HostModeChangeDTO; import com.maibu.core.host.HostWorkRecordCreateDTO; import com.maibu.core.host.MutiPointEntity; +import com.maibu.core.host.ParamDetail; import com.maibu.core.host.PointEntity; import com.maibu.core.ota.DeviceOtaFirmware; import com.maibu.mapper.DevicePlanTaskMapper; @@ -226,12 +228,12 @@ public class NettyDevice extends Connector { return true; } - public synchronized Long canceledTask() { + public synchronized Long canceledTask(String canceledReason) { if (task != null) { Long taskId = task.getId(); task.setTaskStaus(DeviceTaskStaus.CANCELED); task.setUpdateTime(LocalDateTime.now()); - + task.setCanceledReason(canceledReason); // 更新累计里程 updateWorkArea(); devicePlanTaskMapper.saveOrUpdate(task); @@ -600,6 +602,33 @@ public class NettyDevice extends Connector { JsonUtils.toJsonString(payload)); } + public void sendResetCommand(String deviceId, String key) throws MqttException { + + // todo 转换 原先的报文重新组装成上位机的报文格式 + DeviceRemoteControlDTO deviceRemoteControlDTO = new DeviceRemoteControlDTO(); + + ParamDetail data = new ParamDetail(); + + data.setLinear_x(0d); + data.setAngular_z(0d); + data.setChassis_lift(2); + data.setCutter(0); + data.setIgnition(0); + data.setValid_for_ms(250); // 间隔 可调整 + deviceRemoteControlDTO.setData(data); + deviceRemoteControlDTO.setCommand_id(key); + deviceRemoteControlDTO.setSn(deviceId); + deviceRemoteControlDTO.setTimestamp(System.currentTimeMillis()); + deviceRemoteControlDTO + .setMessage_id(Constant.remote_control_msg_prefix + System.currentTimeMillis()); + deviceRemoteControlDTO.setProtocol_version(Constant.protocol_version); + + GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, + String.format(MqttTopic.MOWER_CONTROL_SET, deviceId), + JsonUtils.toJsonString(deviceRemoteControlDTO)); + log.debug("切换自动前复位{},发送遥控指令:{}", deviceId, JsonUtils.toJsonString(deviceRemoteControlDTO)); + } + /** * 急停更新 * @@ -623,4 +652,27 @@ public class NettyDevice extends Connector { JsonUtils.toJsonString(payload)); } + /** + * 开启视频推理 + * + * @param deviceId + * @throws MqttException + */ + public void startVideoStream(String deviceId) throws MqttException { + HostEstopChangeDTO payload = new HostEstopChangeDTO(); + payload.setSn(deviceId); + payload.setTimestamp(System.currentTimeMillis()); + payload.setMessage_id("startVideoStream_" + System.currentTimeMillis()); + payload.setCommand_id("startVideoStreamCommand_ " + System.currentTimeMillis()); + payload.setProtocol_version(Constant.protocol_version); + Map data = new HashMap<>(); + data.put("start", 1); + payload.setData(data); + + GlobalMemory.customMqttDeviceMonitor.publish( + mqttClientId, + String.format(MqttTopic.MOWER_VIDEO_STREAM_SET, deviceId), + JsonUtils.toJsonString(payload)); + } + } diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostRemoteControlReplyDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostRemoteControlReplyDTO.java new file mode 100644 index 0000000..9f56c16 --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/host/HostRemoteControlReplyDTO.java @@ -0,0 +1,16 @@ +package com.maibu.core.host; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class HostRemoteControlReplyDTO extends HostBase { + + private String command_id;// 指令唯一编号 + private Boolean accepted;// 是否接收 + private String code;// 任务动作 OK|INVALID|BUSY|ERROR + + private String message; + +} diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDTO.java index 1facad2..0585ec7 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDTO.java @@ -15,5 +15,7 @@ public class HostTaskStatusDTO extends HostBase{ private HostTaskStatusDetailDTO data; + private String message; + } diff --git a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java index aabbd29..4ed1559 100644 --- a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java @@ -33,6 +33,8 @@ public class GlobalMemory { public static ConcurrentHashMap> modeFutureMap = new ConcurrentHashMap<>(); public static ConcurrentHashMap> eStopFutureMap = new ConcurrentHashMap<>(); + + public static ConcurrentHashMap> remoteControlFutureMap = new ConcurrentHashMap<>(); // public static MqttClientUtil mqttClientUtil; public static CustomMqttDeviceMonitor customMqttDeviceMonitor = null; // 这里面包含了 连我们自己的mqtt 和外部的一些设备,自己的用clientId @@ -122,8 +124,8 @@ public class GlobalMemory { MqttTopic.MOWER_MODE_REPLY, // 模式切换回复 MqttTopic.MOWER_FAULT_POST, // 故障上报 MqttTopic.MOWER_FAULT_RECOVERY_REPLY, // 故障恢复回复 - MqttTopic.MOWER_ESTOP_REPLY // 急停的回复 - )); + MqttTopic.MOWER_ESTOP_REPLY, // 急停的回复 + MqttTopic.MOWER_CONTROL_Reply)); deviceConfig.setHandlerType(Constant.mqttHandleKey); // 唯一的 用于处理上位机mqtt的 customMqttDeviceMonitor.registerDevice(deviceConfig); } diff --git a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java index a8c2a78..5bd649c 100644 --- a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java @@ -27,6 +27,7 @@ import com.maibu.core.business.RegionConsecutiveTaskRecord; import com.maibu.core.business.alarm_center.AlarmMessage; import com.maibu.core.business.dto.ConsecutiveTaskDTO; import com.maibu.core.business.dto.DeviceMapPushDTO; +import com.maibu.core.domain.AjaxResult; import com.maibu.core.domain.entity.SysSite; import com.maibu.core.domain.rule.IotAutoRule; import com.maibu.core.enums.DeviceTaskStaus; @@ -202,6 +203,14 @@ public class SiteMemory { return null; } + public Integer getDeviceSystemMode(String deviceId) { + VehicleMessage v = getVehicleMessage(deviceId); + if (v != null) { + return v.getSystem_mode(); + } + return null; + } + public VehicleMessage getVehicleMessage(String deviceId) { return vehicleMessageMap.get(deviceId); } @@ -508,4 +517,25 @@ public class SiteMemory { return null; } + public boolean canReceiveAutoTask(String deviceId) { + + Integer controlMode = getDeviceControlMode(deviceId); + Integer systemMode = getDeviceSystemMode(deviceId); + + if (controlMode == null) { + return false; + } + + if (controlMode == 0) { + return Objects.equals(systemMode, 2); + } + + if (controlMode == 2) { + return true; + } + + // controlMode == 1、3 或未知值,均不允许 + return false; + } + } diff --git a/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java b/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java index 661b3a7..201676e 100644 --- a/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java +++ b/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java @@ -36,6 +36,7 @@ import com.maibu.core.host.HeartBeatDTO; import com.maibu.core.host.HostLocationRelTimeDTO; import com.maibu.core.host.HostModeChangeReplyDTO; import com.maibu.core.host.HostNavigationReplyDTO; +import com.maibu.core.host.HostRemoteControlReplyDTO; import com.maibu.core.host.HostTaskStatusDTO; import com.maibu.core.host.HostVehicleRelTimeDTO; import com.maibu.core.host.LocationMessage; @@ -513,7 +514,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler { SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); if (siteMemory != null) { - // siteMemory.saveVehicleMessage(deviceId, vehicleRelTimeDTO.getData()); + siteMemory.saveVehicleMessage(deviceId, vehicleRelTimeDTO.getData()); // systemMode = siteMemory.getVehicleMessage(deviceId).getSystemMode(); // Integer oldSystemMode = @@ -544,8 +545,6 @@ public class HostMessageHandler implements CustomMqttMessageHandler { } } - siteMemory.saveVehicleMessage(deviceId, vehicleRelTimeDTO.getData()); - // 故障处理 Long errorCode = vehicleRelTimeDTO.getData().getError_code(); if (errorCode != null && errorCode != 0) { @@ -801,7 +800,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler { task.setTotalTaskDistance(dto.getData().getTotal_distance_m()); task.setTotalTaskTime(dto.getData().getExecution_time_s()); } - Long taskId = nettyDevice.canceledTask(); + Long taskId = nettyDevice.canceledTask(dto.getMessage()); pushTaskChangeMessage(deviceId, taskId, DeviceTaskStaus.CANCELED.toString()); } @@ -907,10 +906,21 @@ public class HostMessageHandler implements CustomMqttMessageHandler { } /** - * 处理控制指令响应 + * 处理远程遥控指令响应 */ private void handleControlReply(String deviceId, String topic, String payload) { - log.debug("【控制响应】deviceId={}, payload={}", deviceId, payload); + log.debug("【远程遥控响应】deviceId={}, payload={}", deviceId, payload); + + HostRemoteControlReplyDTO replyDTO = JsonUtils.parseObject(payload, HostRemoteControlReplyDTO.class); + + if (replyDTO != null && !StringUtils.isEmpty(replyDTO.getCommand_id())) { + CompletableFuture future = GlobalMemory.remoteControlFutureMap.get(replyDTO.getCommand_id()); + + if (future != null && replyDTO != null) { + future.complete(replyDTO.getAccepted()); + } + } + } /** @@ -1132,13 +1142,11 @@ public class HostMessageHandler implements CustomMqttMessageHandler { return "heartbeat_post"; if (remaining.equals("event/error/post")) return "error_post"; - // if (remaining.equals("task/route/post")) return "route_post"; - // if (remaining.equals("task/point/post")) return "point_post"; if (remaining.equals("task/status/post")) return "task_status_post"; if (remaining.equals("action/config/reply")) return "config_reply"; - if (remaining.equals("action/control/reply")) + if (remaining.equals("control/remote/reply")) return "control_reply"; if (remaining.equals("task/target/reply")) return "route_reply"; diff --git a/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java b/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java index 4fcc044..d1d540a 100644 --- a/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java +++ b/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java @@ -51,6 +51,8 @@ public class MqttTopic { /** 远程控制指令下发:前进/后退/转向/割草等(平台->设备),对应 TCP 0x00 remoteControl */ public static final String MOWER_CONTROL_SET = "mower/%s/control/remote/set"; + public static final String MOWER_CONTROL_Reply = "mower/+/control/remote/reply"; + // ==================== 任务管理 ==================== /** 路径规划下发(平台->设备),对应 TCP 0x01 path */ // public static final String MOWER_TASK_ROUTE_SET = "mower/%s/task/route/set"; @@ -133,6 +135,9 @@ public class MqttTopic { /** 设置无遥控器时候的急停回复(设备->平台) */ public static final String MOWER_ESTOP_REPLY = "mower/+/control/emergency_stop/reply"; + /** 开启推流(平台->设备) */ + public static final String MOWER_VIDEO_STREAM_SET = "mower/%s/video/stream/set"; + /** * 格式化 Topic 模板,将 %s 替换为设备ID * diff --git a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java index 5561274..148725e 100644 --- a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java +++ b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java @@ -2,6 +2,7 @@ package com.maibu.controller; import java.time.LocalDate; import java.util.List; +import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.eclipse.paho.client.mqttv3.MqttException; @@ -125,14 +126,10 @@ public class DeviceTaskController extends BaseController { if (siteMemory.hasTask(deviceId)) { return AjaxResult.error("当前设备存在任务!"); } - // Integer mode = siteMemory.getDeviceControlMode(deviceId); - // if (mode == null) { - // return AjaxResult.error("当前设备模式不存在,无法自动任务!"); - // } - // if (mode != 2) { - // String modeStr = switchMode(mode); - // return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!"); - // } + if (!siteMemory.canReceiveAutoTask(deviceId)) { + return AjaxResult.error("当前设备模式无法自动任务,请先切换模式!"); + } + return AjaxResult.success(deviceTaskService.createDeviceTask(dto, getLoginUser().getUsername())); } @@ -158,14 +155,10 @@ public class DeviceTaskController extends BaseController { if (siteMemory.hasTask(deviceId)) { return AjaxResult.error("当前设备存在任务!"); } - // Integer mode = siteMemory.getDeviceControlMode(deviceId); - // if (mode == null) { - // return AjaxResult.error("当前设备模式不存在,无法自动任务!"); - // } - // if (mode != 2) { - // String modeStr = switchMode(mode); - // return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!"); - // } + + if (!siteMemory.canReceiveAutoTask(deviceId)) { + return AjaxResult.error("当前设备模式无法自动任务,请先切换模式!"); + } return AjaxResult.success(deviceTaskService.createRegionDeviceTask(dto, getLoginUser().getUsername())); } @@ -214,14 +207,9 @@ public class DeviceTaskController extends BaseController { if (siteMemory.hasTask(deviceId)) { return AjaxResult.error("当前设备存在任务!"); } - // Integer mode = siteMemory.getDeviceControlMode(deviceId); - // if (mode == null) { - // return AjaxResult.error("当前设备模式不存在,无法自动任务!"); - // } - // if (mode != 2) { - // String modeStr = switchMode(mode); - // return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!"); - // } + if (!siteMemory.canReceiveAutoTask(deviceId)) { + return AjaxResult.error("当前设备模式无法自动任务,请先切换模式!"); + } return AjaxResult.success(deviceTaskService.backToRestPoint(dto, getLoginUser().getUsername())); } @@ -243,14 +231,9 @@ public class DeviceTaskController extends BaseController { if (siteMemory.hasTask(deviceId)) { return AjaxResult.error("当前设备存在任务!"); } - // Integer mode = siteMemory.getDeviceControlMode(deviceId); - // if (mode == null) { - // return AjaxResult.error("当前设备模式不存在,无法自动任务!"); - // } - // if (mode != 2) { - // String modeStr = switchMode(mode); - // return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!"); - // } + if (!siteMemory.canReceiveAutoTask(deviceId)) { + return AjaxResult.error("当前设备模式无法自动任务,请先切换模式!"); + } deviceTaskService.createConsecutiveTasks(dto, getLoginUser().getUsername()); return AjaxResult.success(); } diff --git a/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java b/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java index 9d17123..ae2191a 100644 --- a/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java +++ b/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java @@ -124,7 +124,9 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler { data.setValid_for_ms(250); // 间隔 可调整 deviceRemoteControlDTO.setData(data); deviceRemoteControlDTO - .setCommand_id(Constant.remote_control_cmd_prefix + System.currentTimeMillis()); + .setCommand_id( + Constant.remote_control_cmd_prefix + target.getConnectorId() + "_" + + System.currentTimeMillis()); deviceRemoteControlDTO.setSn(target.getConnectorId()); deviceRemoteControlDTO.setTimestamp(System.currentTimeMillis()); deviceRemoteControlDTO diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java index 354adc0..a84c1c2 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java @@ -22,6 +22,7 @@ import com.maibu.core.business.DevicePlanTask; import com.maibu.core.business.DeviceTaskPlanRule; import com.maibu.core.business.WorkRecord; import com.maibu.core.business.device.NettyDevice; +import com.maibu.core.domain.AjaxResult; import com.maibu.core.enums.DeviceTaskPlanRepeatType; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.mapper.DevicePlanMapper; @@ -64,6 +65,8 @@ public class DevicePlanTaskMonitorService { List list = GlobalMemory.getAllSiteMemory(); if (!CollectionUtils.isEmpty(list)) { list.forEach(siteMemory -> { + if (siteMemory == null) + return; Map> planMap = siteMemory.devicePlanMap; if (!CollectionUtils.isEmpty(planMap.values())) { Iterator iterator = planMap.keySet().iterator(); @@ -73,7 +76,13 @@ public class DevicePlanTaskMonitorService { if (!CollectionUtils.isEmpty(pLlist)) { pLlist.forEach(t -> { try { - createPlanTask(t); + if (siteMemory.hasTask(t.getDeviceId())) { + return; + } + if (!siteMemory.canReceiveAutoTask(t.getDeviceId())) { + return; + } // 检验权限 + createPlanTask(t, siteMemory); } catch (Exception e) { log.error("执行任务生成线程错误", e); } @@ -90,7 +99,7 @@ public class DevicePlanTaskMonitorService { }, 0, 5000, TimeUnit.MILLISECONDS); } - private void createPlanTask(DevicePlan devicePlan) throws Exception { + private void createPlanTask(DevicePlan devicePlan, SiteMemory siteMemory) throws Exception { if (devicePlan.isDayTriggerFlag()) return; // 当天应该创建的全部创建完 DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules(); @@ -98,13 +107,13 @@ public class DevicePlanTaskMonitorService { DeviceTaskPlanRepeatType type = rules.getType(); switch (type) { case DAY: - dayPlan(devicePlan); + dayPlan(devicePlan, siteMemory); break; case WEEK: - weekPlan(devicePlan); + weekPlan(devicePlan, siteMemory); break; case MONTH: - monthPlan(devicePlan); + monthPlan(devicePlan, siteMemory); break; // case ONCE: // oncePlan(devicePlan); @@ -113,10 +122,11 @@ public class DevicePlanTaskMonitorService { } } - public void dayPlan(DevicePlan devicePlan) throws Exception { + public void dayPlan(DevicePlan devicePlan, SiteMemory siteMemory) throws Exception { DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules(); LocalTime nowTime = LocalTime.now(); LocalTime dayTime = LocalTime.parse(rules.getDayTime()); + if (nowTime.isAfter(dayTime)) { DevicePlanTask devicePlanTask = new DevicePlanTask(); devicePlanTask.setPlanId(devicePlan.getId()); @@ -135,12 +145,6 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setOrgId(devicePlan.getOrgId()); devicePlanTask.setSiteId(devicePlan.getSiteId()); devicePlanTaskMapper.insert(devicePlanTask); - SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId()); - - if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) { - log.debug("创建dayPlan切换权限失败!"); - return; - } // 检验权限 siteMemory.addDevicePlanPrepare(devicePlanTask); // 啥时候重置?每日0点? @@ -159,7 +163,7 @@ public class DevicePlanTaskMonitorService { } } - public void weekPlan(DevicePlan devicePlan) throws Exception { + public void weekPlan(DevicePlan devicePlan, SiteMemory siteMemory) throws Exception { DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules(); LocalTime nowTime = LocalTime.now(); List days = devicePlan.getDeviceTaskPlanRules().getDays(); @@ -184,11 +188,7 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setSiteId(devicePlan.getSiteId()); devicePlanTask.setTaskType("");// 待拓展任务类型 devicePlanTaskMapper.insert(devicePlanTask); - SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId()); - if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) { - log.debug("创建weekPlan切换权限失败!"); - return; - } // 检验权限 + siteMemory.addDevicePlanPrepare(devicePlanTask); // 啥时候重置?每日0点? devicePlan.setDayTriggerFlag(true); @@ -205,7 +205,7 @@ public class DevicePlanTaskMonitorService { } } - public void monthPlan(DevicePlan devicePlan) throws Exception { + public void monthPlan(DevicePlan devicePlan,SiteMemory siteMemory) throws Exception { DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules(); List dayOfMonthList = rules.getDayOfMonth(); LocalDate today = LocalDate.now(); @@ -230,12 +230,7 @@ public class DevicePlanTaskMonitorService { devicePlanTask.setOrgId(devicePlan.getOrgId()); devicePlanTask.setSiteId(devicePlan.getSiteId()); devicePlanTaskMapper.insert(devicePlanTask); - SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId()); - if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) { - log.debug("创建monthPlan切换权限失败!"); - return; - } // 检验权限 siteMemory.addDevicePlanPrepare(devicePlanTask); // 啥时候重置?每日0点? devicePlan.setDayTriggerFlag(true); diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java index d33f277..13e3e31 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java @@ -529,10 +529,6 @@ public class DeviceTaskService { public synchronized Long createDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception { SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId()); - boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 - if (!b) { - throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); - } DevicePlanTask task = new DevicePlanTask(); task.setOrgId(dto.getOrgId()); task.setSiteId(dto.getSiteId()); @@ -575,10 +571,10 @@ public class DeviceTaskService { } SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId()); - boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 - if (!b) { - throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); - } + // boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 + // if (!b) { + // throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); + // } if (dto.getOrgId() == null) { SysSite site = sysSiteMapper.selectById(dto.getSiteId()); if (site != null) { @@ -621,7 +617,7 @@ public class DeviceTaskService { if (device != null && device.getTask() != null) { if (dto.isForceCancel()) { device.cancelingTask(); - return device.canceledTask() != null; + return device.canceledTask("人为强制取消") != null; } else { return device.cancelingTask(); } @@ -703,10 +699,10 @@ public class DeviceTaskService { throw new ServiceException(MessageUtils.message("当前机器未配置返回点!")); } - boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 - if (!b) { - throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); - } + // boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 + // if (!b) { + // throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); + // } List restPoints = objectMapper.convertValue( siteMapInfo.getRestPoints(), @@ -756,10 +752,10 @@ public class DeviceTaskService { if (siteMemory == null) { throw new ServiceException(MessageUtils.message("任务下发出错!")); } - boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 - if (!b) { - throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); - } + // boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限 + // if (!b) { + // throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!")); + // } siteMemory.saveRegionConsecutiveTask(dto.getDeviceId(), dto, username); } diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java b/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java index c9e5266..bf7ab55 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java @@ -622,7 +622,10 @@ public class DeviceThreadService { if (isAtRestPoint(deviceId, siteMemory)) { return; } - + // 判断是否自动模式 + if (!siteMemory.canReceiveAutoTask(deviceId)) { + return; + } DeviceTaskCommandDTO dto = new DeviceTaskCommandDTO(); dto.setDeviceId(deviceId); dto.setOrgId(siteMemory.getSysSite().getOrgId()); diff --git a/maibu-service/maibu-iot-service/pom.xml b/maibu-service/maibu-iot-service/pom.xml index 56fb225..9e14cb6 100644 --- a/maibu-service/maibu-iot-service/pom.xml +++ b/maibu-service/maibu-iot-service/pom.xml @@ -101,6 +101,12 @@ + + + io.agora + authentication + 2.1.3 + diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java index 8406774..424e130 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java @@ -301,4 +301,16 @@ public class HostComputerController extends BaseController { return AjaxResult.success(hostComputerService.eStopChange(deviceId, eStop)); } + @GetMapping("/getAgoraToken") + public AjaxResult getAgoraToken(@RequestParam String deviceId) { + + return AjaxResult.success(hostComputerService.getAgoraToken(deviceId)); + } + + @GetMapping("/startVideoStream") + public AjaxResult startVideoStream(@RequestParam String deviceId) { + + return AjaxResult.success(hostComputerService.getAgoraToken(deviceId)); + } + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java index b7d63be..1a663f8 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java @@ -1,20 +1,27 @@ package com.maibu.service.impl; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import com.maibu.constant.Constant; import com.maibu.core.business.device.NettyDevice; import com.maibu.core.host.VehicleMessage; +import com.maibu.core.redis.RedisCache; import com.maibu.exception.ServiceException; import com.maibu.memory.DeviceSessionManager; import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; +import com.maibu.utils.StringUtils; +import io.agora.media.RtcTokenBuilder2; import lombok.extern.slf4j.Slf4j; @Service @@ -24,6 +31,18 @@ public class HostComputerService { @Autowired private DeviceSessionManager deviceSessionManager; + @Value("${agora.appId}") + private String agoraAppId; + + @Value("${agora.appCertificate}") + private String agoraAppCertificate; + + @Value("${agora.tokenExpirationInSeconds}") + private Integer tokenExpirationInSeconds; + + @Value("${agora.privilegeExpirationInSeconds}") + private Integer privilegeExpirationInSeconds; + public void searchDevice(String deviceId) throws Exception { NettyDevice device = deviceSessionManager.getDevice(deviceId); if (device != null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) { @@ -81,17 +100,60 @@ public class HostComputerService { SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + boolean sendRemoteCommand = true; if (siteMemory != null) { VehicleMessage vehicleMessage = siteMemory.getVehicleMessage(deviceId); if (vehicleMessage != null && vehicleMessage.getControl_mode() != null) { Integer nowMode = vehicleMessage.getControl_mode(); - + Integer systemMode = vehicleMessage.getSystem_mode(); if (controlMode.equals(nowMode)) { throw new ServiceException("设备已处于该模式"); } + if (siteMemory.hasTask(deviceId) && Objects.equals(controlMode, 3)) { + throw new ServiceException("设备存在自动任务,请先取消!"); + } + if (Objects.equals(nowMode, 0) && Objects.equals(systemMode, 0)) { + sendRemoteCommand = false; + } } } + // 刚登录切换不下发复位 会被拒绝 + if (sendRemoteCommand) { + String key = Constant.remote_control_cmd_prefix + deviceId + "_" + + System.currentTimeMillis(); + // 创建等待回传的 Future + CompletableFuture resetFuture = new CompletableFuture<>(); + + // 一个设备同时只允许一个模式切换请求 + CompletableFuture oldResetFuture = GlobalMemory.remoteControlFutureMap.putIfAbsent(key, + resetFuture); + + if (oldResetFuture != null) { + throw new ServiceException("设备正在执行复位操作,请稍后再试"); + } + + try { + // 相互切换前 给他重置 + device.sendResetCommand(deviceId, key); + + // 等待设备回传,最多等待 5 秒 + Boolean result = resetFuture.get(5, TimeUnit.SECONDS); + if (!result) { + return false; + } + + } catch (Exception e) { + log.error("切换模式失败", e); + throw new ServiceException("设备模式切换失败"); + + } finally { + // 无论成功、失败还是超时,都清理 Future + GlobalMemory.remoteControlFutureMap.remove(key, resetFuture); + } + // 延时1s再切换 + Thread.sleep(1000); + } // 创建等待回传的 Future CompletableFuture future = new CompletableFuture<>(); @@ -122,4 +184,63 @@ public class HostComputerService { } } + private static final long START_UID = 1000L; + private static final long MAX_UID = Integer.MAX_VALUE; + + private static final AtomicLong AGORA_UID = new AtomicLong(START_UID); + + /** + * 生成 Agora UID + */ + public Integer generateAgoraUid() { + + long uid = AGORA_UID.incrementAndGet(); + + // 超过最大值,重置计数器 + if (uid > MAX_UID) { + AGORA_UID.set(START_UID); + uid = START_UID; + } + + return (int) uid; + } + + public Map getAgoraToken(String deviceId) { + if (StringUtils.isEmpty(deviceId) || agoraAppId == null || agoraAppId.isEmpty() || agoraAppCertificate == null + || agoraAppCertificate.isEmpty()) { + return null; + } + // Generate Token + Integer uid = generateAgoraUid(); + RtcTokenBuilder2 token = new RtcTokenBuilder2(); + String result = token.buildTokenWithUid(agoraAppId, agoraAppCertificate, deviceId, uid, + RtcTokenBuilder2.Role.ROLE_SUBSCRIBER, + tokenExpirationInSeconds, privilegeExpirationInSeconds); + Map map = new HashMap<>(); + map.put("uid", uid); + map.put("token", result); + map.put("appId", agoraAppId); + map.put("appCertificate", agoraAppCertificate); + return map; + } + + public void startVideoStream(String deviceId) { + NettyDevice device = deviceSessionManager.getDevice(deviceId); + + if (device == null || device.getOnlineStatus() == null + || device.getOnlineStatus() == 0) { + throw new ServiceException("设备不在线"); + } + + try { + // 下发指令 + device.startVideoStream(deviceId); + + } catch (Exception e) { + log.error("开启视频流:{}失败", deviceId, e); + throw new ServiceException("急停切换失败"); + + } + } + }