diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + /// + /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java index f4a193a..056cc36 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java @@ -57,17 +57,17 @@ * 停留时间 */ @TableField("STOP_TIME") - private String stopTime; + private Integer stopTime; /** * 报警阈值 */ @TableField("ALARM_VALUE") - private String alarmValue; + private Integer alarmValue; /** * 速度 */ @TableField("SPEED") - private String speed; + private Integer speed; /** * 巡航线序号 */ @@ -88,7 +88,14 @@ */ @TableField("TS") private Date ts; + public BusObserpoiInfo() { + } + public BusObserpoiInfo(Double direction, Double pitch, Integer stopTime) { + this.direction = direction; + this.pitch = pitch; + this.stopTime = stopTime; + } @Override public String toString() { diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java index f4a193a..056cc36 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java @@ -57,17 +57,17 @@ * 停留时间 */ @TableField("STOP_TIME") - private String stopTime; + private Integer stopTime; /** * 报警阈值 */ @TableField("ALARM_VALUE") - private String alarmValue; + private Integer alarmValue; /** * 速度 */ @TableField("SPEED") - private String speed; + private Integer speed; /** * 巡航线序号 */ @@ -88,7 +88,14 @@ */ @TableField("TS") private Date ts; + public BusObserpoiInfo() { + } + public BusObserpoiInfo(Double direction, Double pitch, Integer stopTime) { + this.direction = direction; + this.pitch = pitch; + this.stopTime = stopTime; + } @Override public String toString() { diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java index eeac8b8..e3afbe1 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.baomidou.mybatisplus.extension.service.IService; @@ -30,4 +31,10 @@ ResponseData monitorDetail(Long id); + MonitorBaseInfo selectInfoByDeviceIp(String deviceIp); + + BusMonipoiInfo selectByDeviceIp(String deviceIp); + + void updateBusMonipoiInfo(String deviceIp,int lineNum); + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java index f4a193a..056cc36 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java @@ -57,17 +57,17 @@ * 停留时间 */ @TableField("STOP_TIME") - private String stopTime; + private Integer stopTime; /** * 报警阈值 */ @TableField("ALARM_VALUE") - private String alarmValue; + private Integer alarmValue; /** * 速度 */ @TableField("SPEED") - private String speed; + private Integer speed; /** * 巡航线序号 */ @@ -88,7 +88,14 @@ */ @TableField("TS") private Date ts; + public BusObserpoiInfo() { + } + public BusObserpoiInfo(Double direction, Double pitch, Integer stopTime) { + this.direction = direction; + this.pitch = pitch; + this.stopTime = stopTime; + } @Override public String toString() { diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java index eeac8b8..e3afbe1 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.baomidou.mybatisplus.extension.service.IService; @@ -30,4 +31,10 @@ ResponseData monitorDetail(Long id); + MonitorBaseInfo selectInfoByDeviceIp(String deviceIp); + + BusMonipoiInfo selectByDeviceIp(String deviceIp); + + void updateBusMonipoiInfo(String deviceIp,int lineNum); + } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java index 8bf83e0..9389234 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java @@ -3,6 +3,8 @@ import com.casic.missiles.modular.system.model.BusObserpoiInfo; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; + /** *

* 巡航预置点信息表 服务类 @@ -12,5 +14,34 @@ * @since 2023-04-18 */ public interface IBusObserpoiInfoService extends IService { + List selectByMonitor(String deviceIp, Integer lineNum); + + List selectByMonitor(Long monitorId,Integer lineNum); + + Integer selectMaxNum(Long monitorId,Integer lineNum); + + boolean addPresetByIp(String deviceIp, int presetIndex,int cruiseRoute, + double direction, double pitch, int stopTime, + int alarmValue,int speed,String presetName, + String cruiseName); + + List selectBeforesBySerialNum(String deviceIp,Integer lineNum,Integer serialNum); + + boolean deletePresetBySerials(String deviceIp, int presetIndex,int cruiseRoute ); + + boolean deletePresetByIp(String deviceIp, int presetIndex,int cruiseRoute ); + + BusObserpoiInfo selectByMonitorAndNum(Long monitorId, Integer serialNum,Integer lineNum); + + boolean updateGlobalValues(String deviceIp, Integer stopTime, + Integer alarmValue, Integer speed); + + boolean updateCruise(Long monitorId, String cruiseName,int cruiseRoute ); + + List selectByMonitor(String deviceIp); + + Integer selectByMonitorByCruiseName(Long monitorId,String cruiseName); + + boolean deleteCruise(String deviceIp, String cruiseName,int cruiseRoute ); } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java index f4a193a..056cc36 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java @@ -57,17 +57,17 @@ * 停留时间 */ @TableField("STOP_TIME") - private String stopTime; + private Integer stopTime; /** * 报警阈值 */ @TableField("ALARM_VALUE") - private String alarmValue; + private Integer alarmValue; /** * 速度 */ @TableField("SPEED") - private String speed; + private Integer speed; /** * 巡航线序号 */ @@ -88,7 +88,14 @@ */ @TableField("TS") private Date ts; + public BusObserpoiInfo() { + } + public BusObserpoiInfo(Double direction, Double pitch, Integer stopTime) { + this.direction = direction; + this.pitch = pitch; + this.stopTime = stopTime; + } @Override public String toString() { diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java index eeac8b8..e3afbe1 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.baomidou.mybatisplus.extension.service.IService; @@ -30,4 +31,10 @@ ResponseData monitorDetail(Long id); + MonitorBaseInfo selectInfoByDeviceIp(String deviceIp); + + BusMonipoiInfo selectByDeviceIp(String deviceIp); + + void updateBusMonipoiInfo(String deviceIp,int lineNum); + } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java index 8bf83e0..9389234 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java @@ -3,6 +3,8 @@ import com.casic.missiles.modular.system.model.BusObserpoiInfo; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; + /** *

* 巡航预置点信息表 服务类 @@ -12,5 +14,34 @@ * @since 2023-04-18 */ public interface IBusObserpoiInfoService extends IService { + List selectByMonitor(String deviceIp, Integer lineNum); + + List selectByMonitor(Long monitorId,Integer lineNum); + + Integer selectMaxNum(Long monitorId,Integer lineNum); + + boolean addPresetByIp(String deviceIp, int presetIndex,int cruiseRoute, + double direction, double pitch, int stopTime, + int alarmValue,int speed,String presetName, + String cruiseName); + + List selectBeforesBySerialNum(String deviceIp,Integer lineNum,Integer serialNum); + + boolean deletePresetBySerials(String deviceIp, int presetIndex,int cruiseRoute ); + + boolean deletePresetByIp(String deviceIp, int presetIndex,int cruiseRoute ); + + BusObserpoiInfo selectByMonitorAndNum(Long monitorId, Integer serialNum,Integer lineNum); + + boolean updateGlobalValues(String deviceIp, Integer stopTime, + Integer alarmValue, Integer speed); + + boolean updateCruise(Long monitorId, String cruiseName,int cruiseRoute ); + + List selectByMonitor(String deviceIp); + + Integer selectByMonitorByCruiseName(Long monitorId,String cruiseName); + + boolean deleteCruise(String deviceIp, String cruiseName,int cruiseRoute ); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java index 6c168f3..f05c778 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java @@ -1,5 +1,7 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.core.application.context.AbstractPermissionContext; @@ -7,6 +9,7 @@ import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.casic.missiles.modular.system.dao.BusMonipoiInfoMapper; @@ -15,6 +18,7 @@ import com.casic.missiles.util.DictCodeUtils; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; @@ -42,11 +46,11 @@ } @Override - public Page monitorListPage(Page page, Long stationId, String keyword)throws Exception { + public Page monitorListPage(Page page, Long stationId, String keyword) throws Exception { DataScope dataScope = permissionContext.getAuthService().getLoginUserDataScope(); dataScope.setScopeName("DEPT_ID"); List monitorPointLists = this.baseMapper.monitorListPage(dataScope, stationId, keyword); - for(BusMonipoiInfo busMonipoiInfo:monitorPointLists){ + for (BusMonipoiInfo busMonipoiInfo : monitorPointLists) { DictCodeUtils.convertDictCodeToName(busMonipoiInfo); } page.setRecords(monitorPointLists); @@ -86,4 +90,33 @@ return ResponseData.success(busMonipoiInfo); } + @Override + @Cacheable(value = {"PAN-TILT"}, key = "'monitor_info_ip-'+#deviceIp") + public MonitorBaseInfo selectInfoByDeviceIp(String deviceIp) { + return this.baseMapper.selectInfoByDeviceIp(deviceIp); + } + + @Override + @Cacheable(value = {"PAN-TILT"}, key = "'bus_monitor_info_ip-'+#deviceIp") + public BusMonipoiInfo selectByDeviceIp(String deviceIp) { + QueryWrapper query = new QueryWrapper(); + query.eq("DEVICE_IP", deviceIp); + query.eq("VALID", "0"); + List list = this.list(query); + if (ObjectUtil.isNotEmpty(list)) { + return list.get(0); + } + return null; + } + + + @Override + public void updateBusMonipoiInfo(String deviceIp, int lineNum) { + BusMonipoiInfo busMonipoiInfo=selectByDeviceIp(deviceIp); + if(null!=busMonipoiInfo){ + busMonipoiInfo.setLineNum(lineNum); + this.baseMapper.updateById(busMonipoiInfo); + } + } + } diff --git a/casic-common/pom.xml b/casic-common/pom.xml index 5190667..27e6a55 100644 --- a/casic-common/pom.xml +++ b/casic-common/pom.xml @@ -41,6 +41,11 @@ provided + + org.apache.mina + mina-core + 2.0.4 + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java new file mode 100644 index 0000000..bed1361 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/CommDoorUtil.java @@ -0,0 +1,156 @@ +package com.casic.missiles.weigeng; + + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class CommDoorUtil implements ApplicationRunner { + @Value("${casic.doorips}") + private String doorips; + @Value("${casic.doorsns}") + private String doorsns; + @Value("${casic.monitorids}") + private String monitorids; + @Value("${casic.restartTime}") + private int restartTime; + public final static Map map = new HashMap(); + public static Map flagMap = new HashMap(); + + @Override + public void run(ApplicationArguments args) throws Exception { + if (ObjectUtil.isNotEmpty(doorips)) { + String[] dooripsArr = doorips.split(","); + String[] doorsnsArr = doorsns.split(","); + String[] monitoridsArr = monitorids.split(","); + for (int i = 0; i < dooripsArr.length; i++) { + map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); + flagMap.put(monitoridsArr[i], false); + } + map.put("time", restartTime); + } + } + + + //取消防爆箱控制器报警 + public static void cancelControl() { + try { + if (flagMap.get("control")) { + boolean controlFlag = false; + for (Map.Entry entry : flagMap.entrySet()) { + if (entry.getKey().equals("control")) continue; + controlFlag = controlFlag || entry.getValue(); + } + //若所有云台防爆箱都不报警 则控制箱取消报警 +// if (!controlFlag) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { +// flagMap.put("control", false); +// } +// } + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + //控制云台报警 + public static void controlPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + (!flagMap.get(monitorId))) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) { + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { + flagMap.put(monitorId, true); +// if (!flagMap.get("control")) { +// String controlStr = map.get("control").toString(); +// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { +// flagMap.put("control", true); +// } +// } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //取消云台报警 + public static void cancelPTZ(String monitorId) { + try { + if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && + flagMap.get(monitorId)) { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { + flagMap.put(monitorId, false); + //判断是否取消控制箱报警 +// CommDoorUtil.cancelControl(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重置所有告警 + public static void cancelAllPTZ() { + try { + for (Map.Entry entry : map.entrySet()) { + String controlStr = entry.getValue().toString(); + if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { + flagMap.put(entry.getKey(), false); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + //重启设备 + public static boolean restart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //重启设备 + public static boolean interruptStart(String monitorId) { + try { + String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; + if (ObjectUtil.isNotEmpty(doors)) + if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); + //重新关闭开关上电 + DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); + + Thread.sleep(2 * 60 * 1000); + return true; + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java new file mode 100644 index 0000000..13b32e0 --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/DoorShortUtil.java @@ -0,0 +1,859 @@ +package com.casic.missiles.weigeng; + +import cn.hutool.core.util.ObjectUtil; +import org.springframework.scheduling.annotation.Async; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Async +public class DoorShortUtil { + + + //单个增加授权 + public static boolean addSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2029年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加起止时间设置授权 + public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String beginDate, + String endDate, String startTime, String endTime) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); + } + if (ObjectUtil.isNotEmpty(startTime)) { + pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); + pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); + pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 时间段卡授权 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //单个增加时间设置授权 + public static boolean addsetSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, int type) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** + //增加卡号0D D7 37 00, 通过当前控制器的所有门 + pkt.Reset(); + pkt.functionID = (byte) 0x50; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 29 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + if (type > 1) { + pkt.data[12] = GetHex(type); + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = GetHex(type); + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = GetHex(type); + } + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. + log("1.11 策略权限添加或修改 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //单个删除授权 + public static boolean deleteSingleAcs(String controllerIP, long controllerSN, + long cardNOOfPrivilege, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, + List cardNOOfPrivileges, String type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + for (Long cardNOOfPrivilege : cardNOOfPrivileges) { + pkt.Reset(); + pkt.functionID = (byte) 0x52; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. + log("1.12 权限删除(单个删除) 成功..."); + success = true; + } + } + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //批量删除授权 + public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x54; + pkt.iDevSn = controllerSN; + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); + + recvBuff = pkt.run(); + success = false; + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //这时清空成功 + log("1.13 权限清空(全部清掉) 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //批量授权 + public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + //打开udp连接 + pkt.CommOpen(controllerIP); + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); + int cardCount = cardCodeList.size(); + for (int i = 0; i < cardCount; i++) { + pkt.Reset(); + pkt.functionID = (byte) 0x56; + pkt.iDevSn = controllerSN; + + System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); + //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) + pkt.data[4] = 0x20; + pkt.data[5] = 0x10; + pkt.data[6] = 0x01; + pkt.data[7] = 0x01; + //20 59 12 31 截止日期: 2059年12月31日 + pkt.data[8] = 0x20; + pkt.data[9] = 0x59; + pkt.data[10] = 0x12; + pkt.data[11] = 0x31; + //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] + pkt.data[12] = 0x01; + //01 允许通过 二号门 [对双门, 四门控制器有效] + pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 + //01 允许通过 三号门 [对四门控制器有效] + pkt.data[14] = 0x01; + //01 允许通过 四号门 [对四门控制器有效] + pkt.data[15] = 0x01; + + + System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 + int i2 = i + 1; + System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) + + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + success = true; + } + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); + success = false; + break; + } + } else { + success = false; + break; + } + } + if (success == true) { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); + } else { + log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); + } + + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //远程开门 + public static boolean remoteControllAcs(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + + + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.10 远程开门[功能号: 0x40] ********************************************************************************** + int doorNO = 1; + pkt.Reset(); + pkt.functionID = (byte) 0x40; + pkt.iDevSn = controllerSN; + pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.10 远程开门 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //提取刷卡记录 + public static Map getCardRecords(String controllerIP, long controllerSN) { + + //1.9 提取记录操作 + //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex + //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 + //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + //经过上面三个步骤, 整个提取记录的操作完成 + List> objectList = new ArrayList<>(); + Map resultMap = new HashMap<>(); + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + //打开udp连接 + pkt.CommOpen(controllerIP); + log(String.format("控制器SN = %d \r\n", controllerSN)); + log("1.9 提取记录操作 开始..."); + pkt.Reset(); + pkt.functionID = (byte) 0xB4; + pkt.iDevSn = controllerSN; + long recordIndexGot4GetSwipe = 0x0; + int recordIndexToGet = 0; + recvBuff = pkt.run(); + if (recvBuff != null) { + recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + pkt.Reset(); + pkt.functionID = (byte) 0xB0; + pkt.iDevSn = controllerSN; + long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; + long recordIndexValidGet = 0; + int cnt = 0; + do { + System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + if (recordType == 0) { + break; //没有更多记录 + } + + recordIndexValidGet = recordIndexToGetStart; + //.......对收到的记录作存储处理 + objectList.add(displayRecordInformation(recvBuff)); + + } else { + //提取失败 + System.out.println("*****提取失败"); + break; + } + recordIndexToGetStart++; + } while (cnt++ < 200000); + if (recordIndexValidGet > 0) { + //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 + pkt.Reset(); + pkt.functionID = (byte) 0xB2; + pkt.iDevSn = controllerSN; + System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); + //12 标识(防止误设置) 1 0x55 [固定] + System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); + recvBuff = pkt.run(); + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //完全提取成功.... + log("1.9 完全提取成功 成功..."); + success = true; + } + } + + } + } + //关闭udp连接 + pkt.CommClose(); + resultMap.put("success", success); + resultMap.put("list", objectList); + return resultMap; + } + + + ///

+ /// 显示记录信息 + /// + /// + public static Map displayRecordInformation(byte[] recvBuff) { + Map recordMap = new HashMap<>(); + + long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); + //8-11 最后一条记录的索引号 + //(=0表示没有记录) 4 0x00000000 + long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); + + + //12 记录类型 + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); + + //13 有效性(0 表示不通过, 1表示通过) 1 + int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); + + //14 门号(1,2,3,4) 1 + int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); + + //15 进门/出门(1表示进门, 2表示出门) 1 0x01 + int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); + + //16-19 卡号(类型是刷卡记录时) + //或编号(其他类型记录) 4 + long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); + + + //20-26 刷卡时间: + //年月日时分秒 (采用BCD码)见设置时间部分的说明 + String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[20]), + WgUdpCommShort.getIntByByte(recvBuff[21]), + WgUdpCommShort.getIntByByte(recvBuff[22]), + WgUdpCommShort.getIntByByte(recvBuff[23]), + WgUdpCommShort.getIntByByte(recvBuff[24]), + WgUdpCommShort.getIntByByte(recvBuff[25]), + WgUdpCommShort.getIntByByte(recvBuff[26])); + + //2012.12.11 10:49:59 7 + //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) + //处理复杂信息才用 1 + int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); + + //0=无记录 + //1=刷卡记录 + //2=门磁,按钮, 设备启动, 远程开门记录 + //3=报警记录 1 + //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 + if (recordType == 0) { + log(String.format("索引位=%u 无记录", recordIndex)); + } else if (recordType == 0xff) { + log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); + } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 + { + //卡号 + log(String.format("sn=%d ", sn)); + log(String.format("索引位=%d ", recordIndex)); + log(String.format(" 卡号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); + log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + recordMap.put("sn", sn); + recordMap.put("recordIndex", recordIndex); + recordMap.put("recordCardNO", recordCardNO); + recordMap.put("recordDoorNO", recordDoorNO); + recordMap.put("recordInOrOut", recordInOrOut); + recordMap.put("recordValid", recordValid); + recordMap.put("recordTime", recordTime); + recordMap.put("reason", getReasonDetailChinese(reason)); + } else if (recordType == 2) { + //其他处理 + //门磁,按钮, 设备启动, 远程开门记录 + log(String.format("索引位=%d 非刷卡记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } else if (recordType == 3) { + //其他处理 + //报警记录 + log(String.format("索引位=%d 报警记录", recordIndex)); + log(String.format(" 编号 = %d", recordCardNO)); + log(String.format(" 门号 = %d", recordDoorNO)); + log(String.format(" 时间 = %s", recordTime)); + log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); + } + return recordMap; + } + + public static String getReasonDetailChinese(int Reason) //中文 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 + } + + public static String getReasonDetailEnglish(int Reason) //英文描述 + { + if (Reason > 45) { + return ""; + } + if (Reason <= 0) { + return ""; + } + return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 + } + + public static String RecordDetails[] = + { +//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) +//代码 类型 英文描述 中文描述 + "1", "SwipePass", "Swipe", "刷卡开门", + "2", "SwipePass", "Swipe Close", "刷卡关", + "3", "SwipePass", "Swipe Open", "刷卡开", + "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", + "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", + "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", + "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", + "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", + "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", + "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", + "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", + "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", + "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", + "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", + "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", + "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", + "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", + "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", + "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", + "20", "ValidEvent", "Push Button", "按钮开门", + "21", "ValidEvent", "Push Button Open", "按钮开", + "22", "ValidEvent", "Push Button Close", "按钮关", + "23", "ValidEvent", "Door Open", "门打开[门磁信号]", + "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", + "25", "ValidEvent", "Super Password Open Door", "超级密码开门", + "26", "ValidEvent", "Super Password Open", "超级密码开", + "27", "ValidEvent", "Super Password Close", "超级密码关", + "28", "Warn", "Controller Power On", "控制器上电", + "29", "Warn", "Controller Reset", "控制器复位", + "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", + "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", + "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", + "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", + "34", "Warn", "Threat", "胁迫报警", + "35", "Warn", "Threat Open", "胁迫报警开", + "36", "Warn", "Threat Close", "胁迫报警关", + "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", + "38", "Warn", "Forced Open", "强行闯入报警", + "39", "Warn", "Fire", "火警", + "40", "Warn", "Forced Close", "强制关门", + "41", "Warn", "Guard Against Theft", "防盗报警", + "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", + "43", "Warn", "Emergency Call", "紧急呼救报警", + "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", + "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" + }; + + public static void log(String info) //日志信息 + { + System.out.println(info); + } + + + //常开、常闭 + public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x80; + pkt.iDevSn = controllerSN; + //(设置2号门 在线 开门延时 3秒) + //1―常开[不受刷卡控制]; + //2—常闭[不受刷卡控制]; + //3—在线控制(缺省值:3) + pkt.data[0] = 0x01; //几号门 + if (doorNum == 2) { + pkt.data[0] = 0x02; //几号门 + } else if (doorNum == 4) { + pkt.data[0] = 0x04; //几号门 + } + pkt.data[1] = 0x03; //在线 + if (type == 1) { + pkt.data[1] = 0x01; //常开 + } else if (type == 2) { + pkt.data[1] = 0x02; //常闭 + } + pkt.data[2] = 0x03; //开门延时 + recvBuff = pkt.run(); + if (recvBuff != null) { + success = true; + for (int i = 0; i < 3; i++) { + if (pkt.data[i] != recvBuff[8 + i]) { + success = false; + break; + } + } + if (true) { + //成功时, 返回值与设置一致 + log("1.17 设置门控制参数 成功..."); + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + + //策略设置 + public static boolean setStrage(String controllerIP, + long controllerSN, + int dataType, + String week, + String beginDate, + String endDate, + String beginTime, + String endTime) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x88; + pkt.iDevSn = controllerSN; + + + pkt.data[0] = GetHex(dataType); + //设置开始时间 + pkt.data[1] = 0x20; + pkt.data[2] = 0x20; + pkt.data[3] = 0x01; + pkt.data[4] = 0x01; + if (ObjectUtil.isNotEmpty(beginDate)) { + pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); + pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); + pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); + pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); + } + //设置结束时间 + pkt.data[5] = 0x20; + pkt.data[6] = 0x59; + pkt.data[7] = 0x02; + pkt.data[8] = 0x21; + if (ObjectUtil.isNotEmpty(endDate)) { + pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); + pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); + pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); + pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); + } + //设置周几可以通行 + pkt.data[9] = 0x01; + pkt.data[10] = 0x01; + pkt.data[11] = 0x01; + pkt.data[12] = 0x01; + pkt.data[13] = 0x01; + pkt.data[14] = 0x01; + pkt.data[15] = 0x01; + + if (ObjectUtil.isNotEmpty(week)) { + for (int i = 9; i <= 15; i++) { + if (!week.contains((i - 8) + "")) { + pkt.data[i] = 0x00; + } + } + } + //设置时间段 + pkt.data[16] = 0x00; + pkt.data[17] = 0x00; + if (ObjectUtil.isNotEmpty(beginTime)) { + pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); + pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); + } + pkt.data[18] = 0x23; + pkt.data[19] = 0x59; + if (ObjectUtil.isNotEmpty(endTime)) { + pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); + pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); + } + recvBuff = pkt.run(); + + if (recvBuff != null) { + if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { + //有效开门..... + log("1.20 设置门时间段控制参数 成功..."); + success = true; + } + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + //查询状态 + public static boolean getStatus(String controllerIP, long controllerSN) { + + byte[] recvBuff; + boolean success = false; + WgUdpCommShort pkt = new WgUdpCommShort(); + pkt.iDevSn = controllerSN; + log(String.format("控制器SN = %d \r\n", controllerSN)); + + //打开udp连接 + pkt.CommOpen(controllerIP); + //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** + pkt.Reset(); + pkt.functionID = (byte) 0x20; + pkt.iDevSn = controllerSN; + recvBuff = pkt.run(); + if (recvBuff != null) { + //读取信息成功... + success = true; + log("1.4 查询控制器状态 成功..."); + + //36 故障号 + //等于0 无故障 + //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 + int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); + + //51 V5.46版本支持 控制器当前年 1 0x13 + //52 V5.46版本支持 月 1 0x06 + //53 V5.46版本支持 日 1 0x22 + + String controllerTime; //控制器当前时间 + controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", + WgUdpCommShort.getIntByByte(recvBuff[51]), + WgUdpCommShort.getIntByByte(recvBuff[52]), + WgUdpCommShort.getIntByByte(recvBuff[53]), + WgUdpCommShort.getIntByByte(recvBuff[37]), + WgUdpCommShort.getIntByByte(recvBuff[38]), + WgUdpCommShort.getIntByByte(recvBuff[39])); + } else { + log("1.4 查询控制器状态 失败..."); + success = false; + } + //关闭udp连接 + pkt.CommClose(); + return success; + } + + public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 + { + return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); + } + + +} + + + + + diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java new file mode 100644 index 0000000..b3d037a --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WatchingShortHandler.java @@ -0,0 +1,82 @@ +package com.casic.missiles.weigeng; + + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandlerAdapter; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + + +/** + * Class the extends IoHandlerAdapter in order to properly handle + * connections and the data the connections send + * + * @author Apache MINA Project + */ +public class WatchingShortHandler extends IoHandlerAdapter { + + private Queue queue; + public WatchingShortHandler(Queue queue) { + super(); + this.queue = queue; + } + /** + * 异常来关闭session + */ + @Override + public void exceptionCaught(IoSession session, Throwable cause) + throws Exception { + cause.printStackTrace(); + session.close(true); + } + + /** + * 服务器端收到一个消息 + */ + @Override + public void messageReceived(IoSession session, Object message) + throws Exception { + + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if (validBytes.length == WgUdpCommShort.WGPacketSize) + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + @Override + public void sessionClosed(IoSession session) throws Exception { +// System.out.println("服务器端关闭session..."); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { +// System.out.println("服务器端成功创建一个session..."); + } + + @Override + public void sessionIdle(IoSession session, IdleStatus status) + throws Exception { + // System.out.println("Session idle..."); + } + + @Override + public void sessionOpened(IoSession session) throws Exception { +// System.out.println("服务器端成功开启一个session..."); + } +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java new file mode 100644 index 0000000..f3740ac --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShort.java @@ -0,0 +1,249 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.future.ConnectFuture; +import org.apache.mina.core.service.IoConnector; +import org.apache.mina.core.session.IoSession; +import org.apache.mina.transport.socket.nio.NioDatagramConnector; + +import java.net.InetSocketAddress; +import java.util.LinkedList; +import java.util.Queue; + +public class WgUdpCommShort { //短报文协议 + + public static final int WGPacketSize = 64; //报文长度 + public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 + public static final int ControllerPort = 60000; //控制器端口 + public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 + + public static byte[] longToByte(long number) { + byte[] b = new byte[8]; + for (int i = 0; i < 8; i++) { + b[i] = (byte) (number % 256); + number >>= 8; + } + return b; + } + + //将带符号的bt转换为不带符号的int类型数据 + public static int getIntByByte(byte bt) //bt 转换为无符号的int + { + if (bt < 0) { + return (bt + 256); + } else { + return bt; + } + } + + //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... + //bytlen (1--8), 不在此范围则返回 -1 + public static long getLongByByte(byte[] data, int startIndex, int bytlen) { + long ret = -1; + if ((bytlen >= 1) && (bytlen <= 8)) { + ret = getIntByByte(data[startIndex + bytlen - 1]); + for (int i = 1; i < bytlen; i++) { + ret <<= 8; + ret += getIntByByte(data[startIndex + bytlen - 1 - i]); + } + } + return ret; + } + + + public byte functionID; //功能号 + public long iDevSn; //设备序列号 4字节 + public byte[] data = new byte[56]; //56字节的数据 [含流水号] + + private static long _Global_xid = 0; + protected long _xid = 0; //2011-5-12 15:28:37 + + void GetNewXid() //2011-1-10 14:22:16 获取新的Xid + { + _Global_xid++; + _xid = _Global_xid; //新的值 + } + + static long getXidOfCommand(byte[] cmd) //获取指令中的xid + { + long ret = -1; + if (cmd.length >= WGPacketSize) { + ret = getLongByByte(cmd, 40, 4); + } + return ret; + } + + public WgUdpCommShort() { + Reset(); + } + + public void Reset() //数据复位 + { + for (int i = 0; i < data.length; i++) { + data[i] = 0; + } + } + + public byte[] toByte() //生成64字节指令包 + { + byte[] buff = new byte[WGPacketSize]; + for (int i = 0; i < data.length; i++) { + buff[i] = 0; + } + buff[0] = Type; + buff[1] = functionID; + System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); + System.arraycopy(data, 0, buff, 8, data.length); + + GetNewXid(); + System.arraycopy(longToByte(_xid), 0, buff, 40, 4); + return buff; + } + + + Queue queue; + IoConnector connector; // = new NioDatagramConnector(); + ConnectFuture connFuture; + + public void CommOpen(String ip, int port) { + queue = new LinkedList(); + connector = new NioDatagramConnector(); + connector.setHandler(new WgUdpCommShortHandler(queue)); + connFuture = connector.connect(new InetSocketAddress(ip, port)); + } + + //打开通信连接 + public void CommOpen(String ip) { + CommOpen(ip, ControllerPort); + } + + //关闭通信连接 + public void CommClose() { + try { + IoSession session = connFuture.getSession(); + if (session != null) { + session.close(true); + } + connector.dispose(); + }catch (Exception e){ + e.printStackTrace(); + } + } + + //运行 获取通信数据 + //失败时, 返回 null, 否则为64字节数据 + public byte[] run() { + try { + return getInfo(iDevSn, toByte()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + //通过指定sn和command 获取数据 + public byte[] getInfo(long sn, byte[] command) { + byte[] bytCommand = command; + IoBuffer b; + IoSession session = connFuture.getSession(); + Boolean bSent = false; + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + + int bSuccess = 0; + int tries = 3; + long xid = getXidOfCommand(bytCommand); + byte[] bytget = null; + while ((tries--) > 0) { + long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; + long CommTimeoutMsMin = 300; + long endTicks = startTicks + CommTimeoutMsMin; + if (startTicks > endTicks) { + //System.out.println("超时"); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + continue; + } + long startIndex = 0; + while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { + if (!bSent) //没有发送过.... + { + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + bSent = true; + } + } + } + if (!queue.isEmpty()) { + synchronized (queue) { + bytget = queue.poll(); + } + if ((bytget[0] == bytCommand[0]) //类型一致 + && (bytget[1] == bytCommand[1]) //功能号一致 + && (xid == getXidOfCommand(bytget))) //序列号对应 + { + bSuccess = 1; + break; // return ret; + } else { + //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); + } + } else { + if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { + } else if (startIndex > 10) { + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + startIndex++; + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + } + if (bSuccess > 0) { + break; + } else { + // System.out.println("重试...."); + session = connFuture.getSession(); + if (session != null) { + if (session.isConnected()) { + b = IoBuffer.allocate(bytCommand.length); + b.put(bytCommand); + b.flip(); + session.write(b); + } + } + } + } + + if (bSuccess > 0) { + //System.out.println("通信 成功"); + return bytget; + } else { + //System.out.println("通信 失败...."); + } + return null; + } + +} diff --git a/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java new file mode 100644 index 0000000..add71ec --- /dev/null +++ b/casic-common/src/main/java/com/casic/missiles/weigeng/WgUdpCommShortHandler.java @@ -0,0 +1,72 @@ +package com.casic.missiles.weigeng; + +import org.apache.mina.core.buffer.IoBuffer; +import org.apache.mina.core.service.IoHandler; +import org.apache.mina.core.session.IdleStatus; +import org.apache.mina.core.session.IoSession; + +import java.util.Queue; + +public class WgUdpCommShortHandler implements IoHandler { + + public Queue queue; + + public WgUdpCommShortHandler() { + } + + public WgUdpCommShortHandler(Queue queue) { + super(); + this.queue = queue; + } + + public void exceptionCaught(IoSession session, Throwable e) + throws Exception { + e.printStackTrace(); + session.close(true); + } + + public void messageReceived(IoSession session, Object message) + throws Exception { + IoBuffer io = (IoBuffer) message; + if (io.hasRemaining()) + { + byte[] validBytes = new byte[io.remaining()]; + io.get(validBytes,0,io.remaining()); + if ((validBytes.length == WgUdpCommShort.WGPacketSize) + && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 + { + synchronized (queue) + { + queue.offer(validBytes); + } + } + else + { + //System.out.print("收到无效数据包: ????\r\n"); + } + //System.out.println(""); + } + } + + public void messageSent(IoSession session, Object message) throws Exception { + + } + + public void sessionClosed(IoSession session) throws Exception { + + } + + public void sessionCreated(IoSession session) throws Exception { + + } + + public void sessionIdle(IoSession session, IdleStatus idle) + throws Exception { + + } + + public void sessionOpened(IoSession session) throws Exception { + + } + +} diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java index 04cc752..afe42ba 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/AlarmRecordMapper.java @@ -26,4 +26,12 @@ @Param("dataScope") DataScope dataScope); AlarmRecordResponse detail(@Param("id") Long id); + + void clearByMonitorTime(@Param("monitorId") Long monitorId, + @Param("startTime") String startTime, + @Param("endTime") String endTime); + int clearByMonitor(@Param("monitorId") Long monitorId, + @Param("alarmDirection") Double alarmDirection, + @Param("alarmPitch") Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml index 84883c1..2c3c748 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/dao/mapping/AlarmRecordMapper.xml @@ -83,4 +83,27 @@ AND bs.VALID = 0 AND ar.ID = #{id} + + + + + update alarm_record + set ALARM_STATUS = '1' + where ALARM_STATUS = '0' + and MONITOR_ID = #{monitorId} + and ALARM_DIRECTION = #{alarmDirection} + and ALARM_PITCH = #{alarmPitch} + + diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java index 5fbeeb0..b442d77 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/model/AlarmRule.java @@ -17,6 +17,7 @@ * @author stylefeng123 * @since 2023-04-18 */ +@Data @TableName("alarm_rule") public class AlarmRule extends Model { diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java index b990fb3..e419b7a 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRecordService.java @@ -8,6 +8,7 @@ import com.casic.missiles.modular.system.model.AlarmRecord; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.Date; import java.util.List; /** @@ -26,4 +27,10 @@ AlarmRecordResponse detail(Long id); + boolean listByTime(Long monitorId, Date startTime, Date endTime, String status); + + void clearByMonitorTime(Long monitorId, String startTime, String endTime); + + int clearByMonitor(Long monitorId,Double alarmDirection, Double alarmPitch); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java index c2296a2..39b137c 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/IAlarmRuleService.java @@ -18,4 +18,12 @@ ResponseData configMonitor( AlarmRule alarmRule); + void resetAlarmRule(Long monitorId, Double high); + + void resetAlarmRule(Long monitorId, Double high, + Integer stopTime, Integer speed, + Integer angle); + + AlarmRule selectByMonitor(Long monitorId); + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java index bdb5d2d..84119b2 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRecordServiceImpl.java @@ -2,6 +2,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.core.application.context.AbstractPermissionContext; import com.casic.missiles.core.application.service.AbstractDictService; @@ -16,9 +17,11 @@ import com.casic.missiles.modular.system.service.IAlarmRecordService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.DictEnum; +import com.casic.missiles.weigeng.CommDoorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; import java.util.List; /** @@ -95,4 +98,32 @@ } return null; } + + @Override + public boolean listByTime(Long monitorId, Date startTime, Date endTime, String status) { + QueryWrapper ew = new QueryWrapper<>(); + if (ObjectUtil.isNotEmpty(monitorId)) + ew.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(startTime)) + ew.ge("ALARM_TIME", startTime); + if (ObjectUtil.isNotEmpty(endTime)) + ew.le("ALARM_TIME", endTime); + if (ObjectUtil.isNotEmpty(status)) + ew.eq("ALARM_STATUS", status); + return this.list(ew).size() > 0 ? true : false; + } + + @Override + public void clearByMonitorTime(Long monitorId, String startTime, String endTime) { + this.baseMapper.clearByMonitorTime(monitorId, startTime, endTime); + CommDoorUtil.cancelPTZ(monitorId + ""); + } + + + @Override + public int clearByMonitor(Long monitorId, Double alarmDirection, Double alarmPitch) { + return this.baseMapper.clearByMonitor(monitorId, alarmDirection, alarmPitch); + + } + } diff --git a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java index df86e39..661c5d3 100644 --- a/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java +++ b/casic-data/src/main/java/com/casic/missiles/modular/system/service/impl/AlarmRuleServiceImpl.java @@ -1,15 +1,17 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; -import com.casic.missiles.modular.system.dto.AlarmConfigDTO; -import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.dao.AlarmRuleMapper; +import com.casic.missiles.modular.system.model.AlarmRule; import com.casic.missiles.modular.system.service.IAlarmRuleService; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; +import java.util.Date; + /** *

* 规则设置 服务实现类 @@ -30,4 +32,57 @@ throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } + @Override + public void resetAlarmRule(Long monitorId, Double high) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + alarmRule.setHigh(high); + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + @Override + public void resetAlarmRule(Long monitorId, Double high, Integer stopTime, Integer speed, Integer angle) { + AlarmRule alarmRule = getById(monitorId); + if (ObjectUtil.isNotEmpty(alarmRule)) { + if (ObjectUtil.isNotEmpty(high)) + alarmRule.setHigh(high); + if (ObjectUtil.isNotEmpty(stopTime)) + alarmRule.setStopTime(stopTime); + if (ObjectUtil.isNotEmpty(angle)) + alarmRule.setAngle(angle); + if (ObjectUtil.isNotEmpty(speed)) + alarmRule.setSpeed(speed); + if (ObjectUtil.isEmpty(high) && ObjectUtil.isEmpty(stopTime) && + ObjectUtil.isEmpty(speed) && ObjectUtil.isEmpty(angle)) { + alarmRule.setHigh(null); + alarmRule.setStopTime(null); + alarmRule.setAngle(null); + alarmRule.setSpeed(null); + } + updateById(alarmRule); + } else { + AlarmRule newAlarmRule = new AlarmRule(); + newAlarmRule.setMonitorId(monitorId); + newAlarmRule.setHigh(high); + newAlarmRule.setStopTime(stopTime); + newAlarmRule.setAngle(angle); + newAlarmRule.setSpeed(speed); + newAlarmRule.setTs(new Date()); + save(newAlarmRule); + } + } + + + @Override + public AlarmRule selectByMonitor(Long monitorId) { + return this.getById(monitorId); + } + } diff --git a/casic-server/pom.xml b/casic-server/pom.xml index 9981283..8c68166 100644 --- a/casic-server/pom.xml +++ b/casic-server/pom.xml @@ -56,12 +56,6 @@ 2.0.0 compile - - - org.apache.mina - mina-core - 2.0.4 - com.casic casic-data diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java index 353e135..941768a 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/controller/HCNetController.java @@ -1,436 +1,436 @@ -//package com.casic.missiles.modular.system.controller; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.casic.missiles.model.response.ResponseData; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.dto.SelectDTO; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.weigeng.DoorShortUtil; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.stereotype.Controller; -//import org.springframework.web.bind.annotation.RequestMapping; -//import org.springframework.web.bind.annotation.ResponseBody; -// -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//@Controller -//@RequestMapping("/HCNet") -//public class HCNetController { -// private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); -// -// @Autowired -// private IHCNetService ihcNetService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// -// /** -// * 注册设备 -// * (前端不再调用) -// */ -// @RequestMapping("/register") +package com.casic.missiles.modular.system.controller; + +import cn.hutool.core.util.ObjectUtil; +import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.dto.SelectDTO; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.weigeng.DoorShortUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping("/HCNet") +public class HCNetController { + private static final Logger logger = LoggerFactory.getLogger(HCNetController.class); + + @Autowired + private IHCNetService ihcNetService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + /** + * 注册设备 + * (前端不再调用) + */ + @RequestMapping("/register") + @ResponseBody + public Object register(String userName, String password, String ip) { + Long userId = ihcNetService.register(userName, password, ip); + Map res = new HashMap<>(); + res.put("userId", userId); + if (userId >= 0) { + return ResponseData.success(res); + } else { + String msg = "注册失败"; + return ResponseData.error(msg); + } + } + + /** + * 预览设备 + * (前端不再调用) + */ + @RequestMapping("/preview") + @ResponseBody + public Object preview(Long userId) { + if (userId < 0) { + return ResponseData.error("用户id无效"); + } + Long realHandle = ihcNetService.realHandle(userId); + if (realHandle >= 0) { + return ResponseData.success(realHandle); + } else { + return ResponseData.error("预览失败"); + } + } + + /** + * 根据设备ip获取登录id(服务端id) + * + * @param deviceIp 设备ip + * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 + */ + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeed") + @ResponseBody + public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeed"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(up-上,down-下,left-左,right-右) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @param speed 云台速度 + * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other + */ + @RequestMapping("/controlWithSpeedTest") + @ResponseBody + public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { + logger.info("request controlWithSpeedTest"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 实时云台控制(不带速度) + * + * @param deviceIp 设备ip + * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) + * @param isStop 开始控制还是结束控制 0-开始, 1-结束 + * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other + */ + @RequestMapping("/control") + @ResponseBody + public Object control(String deviceIp, String command, Integer isStop) { + +// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.control(userId.intValue(), command, isStop)) { + return ResponseData.success(); + } else { + return ResponseData.error("控制失败"); + } + } + + /** + * 预置点管理 + * + * @param deviceIp 设备ip + * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) + * @param presetIndex 预置点编号 + * @param direction 水平角度(添加预置点时需要) + * @param pitch 垂直角度(添加预置点时需要) + * @param speed 云台速度(添加预置点时需要)(不再需要) + * @param stopTime 停顿时间(添加预置点时需要) + * @param alarmValue 巡航点阈值 + * @param presetName 预置点名称 + * @param cruiseName 巡航线名称 + * @return + */ + + @RequestMapping("/preset") + @ResponseBody + public Object preset(String deviceIp, String command, String presetIndex, + Integer cruiseRoute, Double direction, + Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, + direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /*** + * + * @param deviceIp 设备ip + * @param command cruiseEdit-编辑;cruiseDelete-删除 + * @param cruiseValue 巡航号值 + * @param cruiseName 巡航号名称 + * @return + */ + @RequestMapping("/cruiseRoute") + @ResponseBody + public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + + /** + * 自动巡航 + * + * @param deviceIp 自动巡航 + * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) + * @return + */ + @RequestMapping("/cruise") + @ResponseBody + public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("设置失败"); + } + } + + /** + * 获取云台实时角度值 + * + * @param deviceIp 设备ip + * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 + */ + @RequestMapping("/getPosition") + @ResponseBody + public Object getPosition(String deviceIp) { + logger.info("request getPosition"); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + boolean res = ihcNetService.getPosition(userId); + if (res) { + return ResponseData.success(); + } else { + return ResponseData.error("请求失败"); + } + } + + /** + * 转到指定角度 + * + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ + @RequestMapping("/toPosition") + @ResponseBody + public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + boolean res; + if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getDeviceType())) { + res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } else { + res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); + } + return res ? ResponseData.success() : ResponseData.error("请求失败"); + } + + /** + * 查询设备预置点 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getPoints") + @ResponseBody + public Object getPoints(String deviceIp, Integer cruiseRoute) { + List list = ihcNetService.getPoints(deviceIp, cruiseRoute); + return ResponseData.success(list); + } + + + /** + * 查询设备路线 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getLines") + @ResponseBody + public Object getLines(String deviceIp) { + List list = ihcNetService.getLines(deviceIp); + return ResponseData.success(list); + } + + /** + * 获取设备参数设置 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/getDeviceConfig") + @ResponseBody + public Object getDeviceConfig(String deviceIp) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.getDeviceConfig(userId); + + } + + /** + * 特殊指令执行复位 + * + * @param deviceIp 设备ip + * @return 预置点序号 + */ + @RequestMapping("/setPreset") + @ResponseBody + public Object setPreset(String deviceIp, String command) { + + + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.setPresetCommand(userId, command); + + } + /** + * 转到指定角度 + * @param deviceIp 设备ip + * @param horizontalAngle 水平角度 + * @param verticalAngle 垂直角度 + * @return 向设备发送旋转指令 + */ +// @RequestMapping("/toPosition") // @ResponseBody -// public Object register(String userName, String password, String ip) { -// Long userId = ihcNetService.register(userName, password, ip); -// Map res = new HashMap<>(); -// res.put("userId", userId); -// if (userId >= 0) { -// return ResponseData.success(res); -// } else { -// String msg = "注册失败"; -// return ResponseData.error(msg); -// } -// } -// -// /** -// * 预览设备 -// * (前端不再调用) -// */ -// @RequestMapping("/preview") -// @ResponseBody -// public Object preview(Long userId) { -// if (userId < 0) { -// return ResponseData.error("用户id无效"); -// } -// Long realHandle = ihcNetService.realHandle(userId); -// if (realHandle >= 0) { -// return ResponseData.success(realHandle); -// } else { -// return ResponseData.error("预览失败"); -// } -// } -// -// /** -// * 根据设备ip获取登录id(服务端id) -// * -// * @param deviceIp 设备ip -// * @return 如果服务端已登录设备,直接返回登录id;否则根据ip查询监控点信息,登录设备 -// */ -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = ihcNetService.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeed") -// @ResponseBody -// public Object controlWithSpeed(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeed"); +// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ // Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { +// if(ObjectUtil.isEmpty(userId) || userId < 0){ // return ResponseData.error("设备注册失败"); // } -// if (ihcNetService.controlWithSpeed(userId.intValue(), command, isStop, speed)) { +// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); +// if(res){ // return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(up-上,down-下,left-左,right-右) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @param speed 云台速度 -// * @return 调用 不需要预览的带速度控制接口 NET_DVR_PTZControlWithSpeed_Other -// */ -// @RequestMapping("/controlWithSpeedTest") -// @ResponseBody -// public Object controlWithSpeedTest(String deviceIp, String command, Integer isStop, Integer speed) { -// logger.info("request controlWithSpeedTest"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.controlWithSpeedTest(userId.intValue(), command, isStop, speed)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 实时云台控制(不带速度) -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(clean-镜头清洁,zoomIn-视频放大,zoonOut-视频缩小) -// * @param isStop 开始控制还是结束控制 0-开始, 1-结束 -// * @return 调用 不需要预览的不带速度控制接口 NET_DVR_PTZControl_Other -// */ -// @RequestMapping("/control") -// @ResponseBody -// public Object control(String deviceIp, String command, Integer isStop) { -// -//// DoorShortUtil.remoteControl("192.168.1.103",153203040,1,isStop); -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.control(userId.intValue(), command, isStop)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("控制失败"); -// } -// } -// -// /** -// * 预置点管理 -// * -// * @param deviceIp 设备ip -// * @param command 控制指令类型(presetAdd-添加预置点,presetDel-删除预置点,toPreset-转到预置点) -// * @param presetIndex 预置点编号 -// * @param direction 水平角度(添加预置点时需要) -// * @param pitch 垂直角度(添加预置点时需要) -// * @param speed 云台速度(添加预置点时需要)(不再需要) -// * @param stopTime 停顿时间(添加预置点时需要) -// * @param alarmValue 巡航点阈值 -// * @param presetName 预置点名称 -// * @param cruiseName 巡航线名称 -// * @return -// */ -// -// @RequestMapping("/preset") -// @ResponseBody -// public Object preset(String deviceIp, String command, String presetIndex, -// Integer cruiseRoute, Double direction, -// Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.preset(userId.intValue(), command, presetIndex, cruiseRoute, -// direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /*** -// * -// * @param deviceIp 设备ip -// * @param command cruiseEdit-编辑;cruiseDelete-删除 -// * @param cruiseValue 巡航号值 -// * @param cruiseName 巡航号名称 -// * @return -// */ -// @RequestMapping("/cruiseRoute") -// @ResponseBody -// public Object cruiseRoute(String deviceIp, String command, Integer cruiseValue, String cruiseName) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// if (ihcNetService.cruiseRoute(userId.intValue(), command, cruiseValue, cruiseName, deviceIp)) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// -// /** -// * 自动巡航 -// * -// * @param deviceIp 自动巡航 -// * @param command 控制指令类型(start-开始自动巡航,stop-停止自动巡航) -// * @return -// */ -// @RequestMapping("/cruise") -// @ResponseBody -// public Object cruise(String deviceIp, String command, Integer cruiseRoute, Integer interval) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.cruise(userId.intValue(), command, cruiseRoute, interval); -// if (res) { -// return ResponseData.success(); -// } else { -// return ResponseData.error("设置失败"); -// } -// } -// -// /** -// * 获取云台实时角度值 -// * -// * @param deviceIp 设备ip -// * @return 向设备发送查询指令,在回调函数中通过websocket向前端发送角度值 -// */ -// @RequestMapping("/getPosition") -// @ResponseBody -// public Object getPosition(String deviceIp) { -// logger.info("request getPosition"); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// boolean res = ihcNetService.getPosition(userId); -// if (res) { -// return ResponseData.success(); -// } else { +// }else{ // return ResponseData.error("请求失败"); // } // } -// -// /** -// * 转到指定角度 -// * -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -// @RequestMapping("/toPosition") -// @ResponseBody -// public Object angle(String deviceIp, String horizontalAngle, String verticalAngle) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// boolean res; -// if (ObjectUtil.isNotEmpty(monipoiInfo) && "1".equals(monipoiInfo.getType())) { -// res = ihcNetService.setPosition(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } else { -// res = ihcNetService.setPositionNew(userId, Double.valueOf(horizontalAngle), Double.valueOf(verticalAngle)); -// } -// return res ? ResponseData.success() : ResponseData.error("请求失败"); -// } -// -// /** -// * 查询设备预置点 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getPoints") -// @ResponseBody -// public Object getPoints(String deviceIp, Integer cruiseRoute) { -// List list = ihcNetService.getPoints(deviceIp, cruiseRoute); -// return ResponseData.success(list); -// } -// -// -// /** -// * 查询设备路线 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getLines") -// @ResponseBody -// public Object getLines(String deviceIp) { -// List list = ihcNetService.getLines(deviceIp); -// return ResponseData.success(list); -// } -// -// /** -// * 获取设备参数设置 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/getDeviceConfig") -// @ResponseBody -// public Object getDeviceConfig(String deviceIp) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.getDeviceConfig(userId); -// -// } -// -// /** -// * 特殊指令执行复位 -// * -// * @param deviceIp 设备ip -// * @return 预置点序号 -// */ -// @RequestMapping("/setPreset") -// @ResponseBody -// public Object setPreset(String deviceIp, String command) { -// -// -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.setPresetCommand(userId, command); -// -// } -// /** -// * 转到指定角度 -// * @param deviceIp 设备ip -// * @param horizontalAngle 水平角度 -// * @param verticalAngle 垂直角度 -// * @return 向设备发送旋转指令 -// */ -//// @RequestMapping("/toPosition") -//// @ResponseBody -//// public Object angle(String deviceIp,String horizontalAngle, String verticalAngle){ -//// Long userId = getUserIdByIp(deviceIp); -//// if(ObjectUtil.isEmpty(userId) || userId < 0){ -//// return ResponseData.error("设备注册失败"); -//// } -//// boolean res = ihcNetService.setPosition(userId,Double.valueOf(horizontalAngle),Double.valueOf(verticalAngle)); -//// if(res){ -//// return ResponseData.success(); -//// }else{ -//// return ResponseData.error("请求失败"); -//// } -//// } -// -// -// /** -// * 设备升级特殊定制指令 -// * -// * @param deviceIp ip -// * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 -// * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) -// * @return -// */ -// @RequestMapping("/specialControl") -// @ResponseBody -// public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// -// -//// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); -//// return ResponseData.success(); -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return ResponseData.error("设备注册失败"); -// } -// return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? -// ResponseData.success() : ResponseData.error("设置失败"); -// } -// -// -// /** -// * 一键开闭告警 -// * -// * @return 预置点序号 -// */ -// @RequestMapping("/alarmOperate") -// @ResponseBody -// public Object alarmOperate(String command) { -// -// return ihcNetService.alarmOperate(command); -// -// } -// -// -// /** -// * 掉电重启 -// * -// * @return -// */ -// @RequestMapping("/reStart") -// @ResponseBody -// public Object reStart(String doorIp, String sn) { -// -// try { -// if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { -// //重新上电需要间隔20秒 -// Thread.sleep(20 * 1000); -// //重新关闭开关上电 -// return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// -// return false; -// } -//} + + + /** + * 设备升级特殊定制指令 + * + * @param deviceIp ip + * @param command 控制指令类型(7、云台节点地址配置8、风险点局部扫描角度配置9、本地报警持续时间配置 + * 10、巡航点停留时间配置11、自动复位设置12、预置点执行完毕应答) + * @return + */ + @RequestMapping("/specialControl") + @ResponseBody + public Object specialControl(String deviceIp, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + + +// DoorShortUtil.remoteControl("192.168.1.99", 253219003, 2, 2); +// return ResponseData.success(); + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return ResponseData.error("设备注册失败"); + } + return ihcNetService.specialControl(userId.intValue(), command, value, speed, stopTime, alarmValue) ? + ResponseData.success() : ResponseData.error("设置失败"); + } + + + /** + * 一键开闭告警 + * + * @return 预置点序号 + */ + @RequestMapping("/alarmOperate") + @ResponseBody + public Object alarmOperate(String command) { + + return ihcNetService.alarmOperate(command); + + } + + + /** + * 掉电重启 + * + * @return + */ + @RequestMapping("/reStart") + @ResponseBody + public Object reStart(String doorIp, String sn) { + + try { + if (DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 1)) { + //重新上电需要间隔20秒 + Thread.sleep(20 * 1000); + //重新关闭开关上电 + return DoorShortUtil.remoteControl(doorIp, Long.valueOf(sn), 2, 2); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return false; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java index 16cf902..da03e4f 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/dto/TaskCommon.java @@ -2,6 +2,7 @@ import com.casic.missiles.modular.system.task.AutoCruiseResertTask; //import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @@ -14,7 +15,7 @@ @Component public class TaskCommon { -// public static volatile Map threadMap; + public static volatile Map threadMap; public static volatile Map threadResertMap; @PostConstruct diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java index 9d9c494..c2add20 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/service/impl/HCNetServiceImpl.java @@ -1,2127 +1,1964 @@ -//package com.casic.missiles.modular.system.service.impl; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.core.util.ObjectUtil; -//import com.casic.missiles.modular.system.cache.ICache; -//import com.casic.missiles.modular.system.dto.*; -//import com.casic.missiles.modular.system.es.DataGasEs; -//import com.casic.missiles.modular.system.model.AlarmRecord; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.model.DataGas; -//import com.casic.missiles.modular.system.service.*; -//import com.casic.missiles.modular.system.task.AutoCruiseResertTask; -//import com.casic.missiles.modular.system.task.AutoCruiseTask; -//import com.casic.missiles.modular.system.util.PoolConfig; -//import com.casic.missiles.modular.system.util.WebSocket; -//import com.casic.missiles.modular.weigeng.CommDoorUtil; -//import com.sun.jna.Memory; -//import com.sun.jna.NativeLong; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.annotation.Value; -//import org.springframework.stereotype.Service; -//import org.springframework.transaction.annotation.Transactional; -// -//import java.io.IOException; -//import java.lang.ref.SoftReference; -//import java.math.BigDecimal; -//import java.util.*; -//import java.util.stream.Collectors; -// -// -//@Service -//public class HCNetServiceImpl implements IHCNetService { -// -// private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); -// -// private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; -// -// private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); -// -// private Long timestampCollcect; -// -// //默认复位时间 -// private static final Integer delayTime = 7200; -// -// //特殊预置点号数组 -// private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; -// -// public Long getTimestampCollcect() { -// return timestampCollcect; -// } -// -// public void setTimestampCollcect(Long timestampCollcect) { -// this.timestampCollcect = timestampCollcect; -// } -// -// @Autowired -// private IDataGasService dataGasService; -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IBusObserpoiInfoService obserpoiInfoService; -// @Autowired -// private IAlarmRuleService alarmRuleService; -// @Autowired -// private IAlarmRecordService alarmRecordService; -// @Autowired -// private WebSocket webSocket; -// @Value("${casic.panTilt.defaultStoptime:5}") -// private String defaultStoptime; -// @Value("${casic.alarmvalue}") -// private String alarmvalue; -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Autowired -// private PoolConfig threadPoolTaskExecutor; -// -// -// /** -// * 注册设备 -// */ -// @Override -// public Long register(String userName, String password, String deviceIp) { -// -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { -// return deviceInfo.getUserId(); +package com.casic.missiles.modular.system.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.*; +import com.casic.missiles.modular.system.es.DataGasEs; +import com.casic.missiles.modular.system.model.*; +import com.casic.missiles.modular.system.service.*; +import com.casic.missiles.modular.system.task.AutoCruiseResertTask; +import com.casic.missiles.modular.system.task.AutoCruiseTask; +import com.casic.missiles.modular.system.util.PoolConfig; +import com.casic.missiles.modular.system.util.WebSocket; +import com.casic.missiles.weigeng.CommDoorUtil; +import com.sun.jna.Memory; +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.*; +import java.util.stream.Collectors; + + +@Service +public class HCNetServiceImpl implements IHCNetService { + + private static final Logger logger = LoggerFactory.getLogger(HCNetServiceImpl.class); + + private static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; + + private HCNetSDK.FSerialDataCallBack fSerialDataCallBack = new SerialDataCallBack(); + + private Long timestampCollcect; + + //默认复位时间 + private static final Integer delayTime = 7200; + + //特殊预置点号数组 + private static final Integer[] presets = {65, 67, 68, 69, 70, 72, 73, 87, 88}; + + public Long getTimestampCollcect() { + return timestampCollcect; + } + + public void setTimestampCollcect(Long timestampCollcect) { + this.timestampCollcect = timestampCollcect; + } + + @Autowired + private IDataGasService dataGasService; + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IBusObserpoiInfoService obserpoiInfoService; + @Autowired + private IAlarmRuleService alarmRuleService; + @Autowired + private IAlarmRecordService alarmRecordService; + @Autowired + private WebSocket webSocket; + @Value("${casic.panTilt.defaultStoptime:5}") + private String defaultStoptime; + @Value("${casic.alarmvalue}") + private String alarmvalue; + @Value("${casic.presetInterval}") + private int presetInterval; + @Autowired + private PoolConfig threadPoolTaskExecutor; + + + /** + * 注册设备 + */ + @Override + public Long register(String userName, String password, String deviceIp) { + + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() >= 0) { + return deviceInfo.getUserId(); + } + + if (!hCNetSDK.NET_DVR_Init()) { + System.out.println("初始化失败"); + return -1L; + } + + //注册之前先注销已注册的用户,预览情况下不可注销 +// if (lUserID.longValue() > -1) { +// //先注销 +// hCNetSDK.NET_DVR_Logout(lUserID); +// lUserID = new NativeLong(-1); // } -// -// if (!hCNetSDK.NET_DVR_Init()) { -// System.out.println("初始化失败"); -// return -1L; -// } -// -// //注册之前先注销已注册的用户,预览情况下不可注销 -//// if (lUserID.longValue() > -1) { -//// //先注销 -//// hCNetSDK.NET_DVR_Logout(lUserID); -//// lUserID = new NativeLong(-1); -//// } -// -// // 注册 -// HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); -// int iPort = 8000; -// //System.out.println("注册,设备IP:"+deviceIp); -// NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); -// long userId = lUserID.longValue(); -// if (userId <= -1) { -// int error = hCNetSDK.NET_DVR_GetLastError(); -// logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); -// } else { -// logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); -// } -// DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); -// return userId; -// } -// -// /** -// * 预览设备 -// */ -// @Override -// public Long realHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { -// return deviceInfo.getRealHandle(); -// } -// -// HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); -// // 通道数固定为1 -// m_strClientInfo.lChannel = new NativeLong(1); -// NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); -// } -// -// return m_lRealHandle.longValue(); -// } -// -// /** -// * 建立透明通道 -// */ -// @Override -// public Long serialHandle(Long userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// return deviceInfo.getSerialHandle(); -// } -// -// NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (m_lSerialHandle.longValue() >= 0) { -// logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); -// } -// } -// return m_lSerialHandle.longValue(); -// } -// -// /** -// * 停止透明通道 -// */ -// private boolean stopSerialHandle(Long serialHandle) { -// boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); -// if (res) { -// logger.info("stop transparent channel"); -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); -// DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); -// } -// return res; -// } -// -// /** -// * 向透明通道发送数据 -// */ -// @Override -// public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { -// if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { -// return false; -// } -// // logger.info("send" + System.currentTimeMillis()); -// return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); -// } -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "up": -// iPTZCommand = HCNetSDK.TILT_UP; -// break; -// case "down": -// iPTZCommand = HCNetSDK.TILT_DOWN; -// break; -// case "left": -// iPTZCommand = HCNetSDK.PAN_LEFT; -// break; -// case "right": -// iPTZCommand = HCNetSDK.PAN_RIGHT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// boolean stopRes = false; -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// -// try { -// stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// -// } -// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -// if (stopRes) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(300); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// -// /** -// * 带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -//// @Override -//// public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { -//// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -//// int iPTZCommand = -1; -//// switch (command) { -//// case "up": -//// iPTZCommand = HCNetSDK.TILT_UP; -//// break; -//// case "down": -//// iPTZCommand = HCNetSDK.TILT_DOWN; -//// break; -//// case "left": -//// iPTZCommand = HCNetSDK.PAN_LEFT; -//// break; -//// case "right": -//// iPTZCommand = HCNetSDK.PAN_RIGHT; -//// break; -//// default: -//// break; -//// } -//// if (iPTZCommand <= -1) { -//// return false; -//// } -//// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -//// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -//// stopSerialHandle(deviceInfo.getSerialHandle()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// -//// } -//// logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); -//// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); -//// if (isStop == 1) { -//// serialHandle(deviceInfo.getUserId()); -//// try { -//// Thread.sleep(500); -//// } catch (Exception e) { -//// e.printStackTrace(); -//// } -//// } -//// -//// return res; -//// } -// @Override -// public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// if (isStop == 1) { -// // 停止 -// return sendStopCommand(serialHandle); -// } else { -// switch (command) { -// case "up": -// return sendUpCommand(serialHandle, speed); -// case "down": -// return sendDownCommand(serialHandle, speed); -// case "left": -// return sendLeftCommand(serialHandle, speed); -// case "right": -// return sendRightCommand(serialHandle, speed); -// default: -// break; -// } -// } -// return false; -// } -// -// private boolean sendUpCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendDownCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendLeftCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendRightCommand(Long serialHandle, int speed) { -// int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStartCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// private boolean sendStopCleanCommand(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //设置预置位 -// private boolean setPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //调用预置位 -// private boolean sendPreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //删除预置位 -// private boolean deletePreset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 -// private boolean nodeConfig(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 -// private boolean riskPointAngleSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 -// private boolean alarmTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? -// //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF -// private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { -// int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 -// private boolean autoReset(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 -// private boolean patrolSpeedSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 -// private boolean patrolStopTimeSet(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开指示激光指令格式:FF add 00 91 01 00 SUM -// //关闭指示激光指令格式:FF add 00 91 00 00 SUM -// private boolean laserControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //打开本地报警指令格式:FF add 00 90 02 00 SUM -// //关闭本地报警指令格式:FF add 00 90 03 00 SUM -// private boolean alarmControl(Long serialHandle, int index) { -// int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 -// private boolean deviceMark(Long serialHandle, int index) { -// int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; -// int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 -// private boolean softReset(Long serialHandle) { -// int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; -// int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; -// Pointer pointer = intArrayToPointer(command); -// return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); -// } -// -// -// @Override -// public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// switch (command) { -// case "03": -// return setPreset(serialHandle, value); -// case "05": -// return deletePreset(serialHandle, value); -// case "07": -// return sendPreset(serialHandle, value); -// case "90": -// return alarmControl(serialHandle, value); -//// case "91": -//// return laserControl(serialHandle, value); -// case "92": -// return deviceMark(serialHandle, value); -// case "93": -// return nodeConfig(serialHandle, value); -// case "94": -//// return riskPointAngleSet(serialHandle, value); -// return riskPointAngleSetWhole(userId, serialHandle, value); -// case "95": -// return alarmTimeSet(serialHandle, value); -// case "96": -// return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); -// case "97": -// return autoReset(serialHandle, value); -// case "99": -//// return patrolSpeedSet(serialHandle, value); -// return patrolSpeedSetWhole(userId, serialHandle, value); -// case "9A": -//// return patrolStopTimeSet(serialHandle, value); -// return patrolStopTimeSetWhole(userId, serialHandle, value); -// case "6592": -// return preset0(serialHandle); -// case "65126": -// return allCruise(serialHandle); -// case "68": -// return setWholeAlarmValue(userId, serialHandle, value); -// case "restart": -// return restart(userId); -// case "9C": -// return softReset(serialHandle); -// default: -// break; -// } -// return false; -// } -// -// -// @Override -// public boolean interruptStart(String deviceIp) { -// -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); -// } -// return false; -// } -// -// @Override -// public boolean alarmOperate(String command) { -// List deviceCommonList = DeviceCommom.deviceCommonList; -// switch (command) { -// //关闭告警 -// case "0": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 3); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + + // 注册 + HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo = new HCNetSDK.NET_DVR_DEVICEINFO_V30(); + int iPort = 8000; + //System.out.println("注册,设备IP:"+deviceIp); + NativeLong lUserID = hCNetSDK.NET_DVR_Login_V30(deviceIp, (short) iPort, userName, password, m_strDeviceInfo); + long userId = lUserID.longValue(); + if (userId <= -1) { + int error = hCNetSDK.NET_DVR_GetLastError(); + logger.debug(deviceIp.concat("register error, error code: ").concat(String.valueOf(error))); + } else { + logger.info(deviceIp.concat("register success, userId=").concat(String.valueOf(userId))); + } + DeviceCommom.addOrUpdateDeviceInfo(deviceIp, userId, -1L, -1L); + return userId; + } + + /** + * 预览设备 + */ + @Override + public Long realHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getRealHandle()) && deviceInfo.getRealHandle() >= 0) { + return deviceInfo.getRealHandle(); + } + + HCNetSDK.NET_DVR_CLIENTINFO m_strClientInfo = new HCNetSDK.NET_DVR_CLIENTINFO(); + // 通道数固定为1 + m_strClientInfo.lChannel = new NativeLong(1); + NativeLong m_lRealHandle = hCNetSDK.NET_DVR_RealPlay_V30(new NativeLong(userId), m_strClientInfo, null, null, true); + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + logger.info(deviceInfo.getDeviceIp().concat("realhandle success ,userId=").concat(String.valueOf(m_lRealHandle))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, m_lRealHandle.longValue(), null); + } + + return m_lRealHandle.longValue(); + } + + /** + * 建立透明通道 + */ + @Override + public Long serialHandle(Long userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + return deviceInfo.getSerialHandle(); + } + + NativeLong m_lSerialHandle = hCNetSDK.NET_DVR_SerialStart(new NativeLong(userId), new NativeLong(2), fSerialDataCallBack, 0); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (m_lSerialHandle.longValue() >= 0) { + logger.info(deviceInfo.getDeviceIp().concat("build transparent channel success, serialHandle=").concat(String.valueOf(m_lSerialHandle.longValue()))); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), userId, null, m_lSerialHandle.longValue()); + } + } + return m_lSerialHandle.longValue(); + } + + /** + * 停止透明通道 + */ + private boolean stopSerialHandle(Long serialHandle) { + boolean res = hCNetSDK.NET_DVR_SerialStop(new NativeLong(serialHandle)); + if (res) { + logger.info("stop transparent channel"); + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(serialHandle); + DeviceCommom.addOrUpdateDeviceInfo(deviceInfo.getDeviceIp(), deviceInfo.getUserId(), deviceInfo.getRealHandle(), -1L); + } + return res; + } + + /** + * 向透明通道发送数据 + */ + @Override + public boolean serialSend(Long serialHandle, Pointer pointer, Integer size) { + if (ObjectUtil.isEmpty(serialHandle) || serialHandle < 0) { + return false; + } + // logger.info("send" + System.currentTimeMillis()); + return hCNetSDK.NET_DVR_SerialSend(new NativeLong(serialHandle), new NativeLong(1), pointer, size); + } + + /** + * 带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean controlWithSpeed(Integer userId, String command, Integer isStop, Integer speed) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "up": + iPTZCommand = HCNetSDK.TILT_UP; + break; + case "down": + iPTZCommand = HCNetSDK.TILT_DOWN; + break; + case "left": + iPTZCommand = HCNetSDK.PAN_LEFT; + break; + case "right": + iPTZCommand = HCNetSDK.PAN_RIGHT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + boolean stopRes = false; + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + + try { + stopRes = stopSerialHandle(deviceInfo.getSerialHandle()); + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + + } + logger.info("device control, serialHandle = " + deviceInfo.getSerialHandle()); + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, speed); + if (stopRes) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(300); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + @Override + public boolean controlWithSpeedTest(Integer userId, String command, Integer isStop, Integer speed) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + if (isStop == 1) { + // 停止 + return sendStopCommand(serialHandle); + } else { + switch (command) { + case "up": + return sendUpCommand(serialHandle, speed); + case "down": + return sendDownCommand(serialHandle, speed); + case "left": + return sendLeftCommand(serialHandle, speed); + case "right": + return sendRightCommand(serialHandle, speed); + default: + break; + } + } + return false; + } + + private boolean sendUpCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x08 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x08, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendDownCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x10 + 0x00 + speed) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x10, 0x00, speed, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendLeftCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x04 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x04, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendRightCommand(Long serialHandle, int speed) { + int sum = (0x01 + 0x00 + 0x02 + speed + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x02, speed, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x00 + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStartCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x09 + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x09, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + private boolean sendStopCleanCommand(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x0b + 0x00 + 0x01) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x0b, 0x00, 0x01, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //设置预置位 + private boolean setPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x03 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x03, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //调用预置位 + private boolean sendPreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x07 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x07, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //删除预置位 + private boolean deletePreset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x05 + index / 256 + index % 256) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x05, index / 256, index % 256, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //云台节点配置 FF add 00 93 XX 00 SUM,add需要实时读取 + private boolean nodeConfig(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x93 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x93, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //风险点局部扫描角度配置FF add 00 94 XX 00 SUM,add需要实时读取 其中,index角度为实际扫描偏离角度的10倍 + private boolean riskPointAngleSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x94 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x94, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //本地报警持续时间配置FF add 00 95 XX 00 SUM,add需要实时读取 + private boolean alarmTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x95 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x95, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //巡航点停留时间配置FF add 00 96 MM NN XX YY ZZ SUM,add需要实时读取??? + //ZZ为报警阈值设置参数,实际报警阈值为ZZ*100,ZZ配置范围:0x01~0xFF + private boolean stopTimeSet(Long serialHandle, int index, int stopTime, int speed, int alarmValue) { + int sum = (0x01 + 0x00 + 0x96 + index / 256 + index % 256 + stopTime + speed + alarmValue / 100) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x96, index / 256, index % 256, stopTime, speed, alarmValue / 100, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //自动复位设置FF add 00 97 XX 00 SUM,add需要实时读取 + private boolean autoReset(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x97 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x97, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检速度设置FF add 00 99 XX 00 SUM,add需要实时读取 + private boolean patrolSpeedSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x99 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x99, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //一键巡检驻留时间设置FF add 00 9A XX 00 SUM,add需要实时读取 + private boolean patrolStopTimeSet(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x9A + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9A, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开指示激光指令格式:FF add 00 91 01 00 SUM + //关闭指示激光指令格式:FF add 00 91 00 00 SUM + private boolean laserControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x91 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x91, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //打开本地报警指令格式:FF add 00 90 02 00 SUM + //关闭本地报警指令格式:FF add 00 90 03 00 SUM + private boolean alarmControl(Long serialHandle, int index) { + int sum = (0x01 + 0x00 + 0x90 + index + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x90, index, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + //设备标定指令FF add 00 92 01 00 SUM,add需要实时读取 + private boolean deviceMark(Long serialHandle, int index) { + int sum = (index + 0x00 + 0x92 + 0x01 + 0x00) % 0x100; + int[] command = {0xff, index, 0x00, 0x92, 0x01, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + //宇视通 软复位 add 00 9C 00 00 SUM,add需要实时读取 + private boolean softReset(Long serialHandle) { + int sum = (0x01 + 0x00 + 0x9C + 0x00 + 0x00) % 0x100; + int[] command = {0xff, 0x01, 0x00, 0x9C, 0x00, 0x00, sum}; + Pointer pointer = intArrayToPointer(command); + return serialSend(serialHandle, pointer, (int) ((Memory) pointer).getSize()); + } + + + @Override + public boolean specialControl(Integer userId, String command, Integer value, Integer speed, Integer stopTime, Integer alarmValue) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + switch (command) { + case "03": + return setPreset(serialHandle, value); + case "05": + return deletePreset(serialHandle, value); + case "07": + return sendPreset(serialHandle, value); + case "90": + return alarmControl(serialHandle, value); +// case "91": +// return laserControl(serialHandle, value); + case "92": + return deviceMark(serialHandle, value); + case "93": + return nodeConfig(serialHandle, value); + case "94": +// return riskPointAngleSet(serialHandle, value); + return riskPointAngleSetWhole(userId, serialHandle, value); + case "95": + return alarmTimeSet(serialHandle, value); + case "96": + return paramsSet(userId, serialHandle, value, stopTime, speed, alarmValue); + case "97": + return autoReset(serialHandle, value); + case "99": +// return patrolSpeedSet(serialHandle, value); + return patrolSpeedSetWhole(userId, serialHandle, value); + case "9A": +// return patrolStopTimeSet(serialHandle, value); + return patrolStopTimeSetWhole(userId, serialHandle, value); + case "6592": + return preset0(serialHandle); + case "65126": + return allCruise(serialHandle); + case "68": + return setWholeAlarmValue(userId, serialHandle, value); + case "restart": + return restart(userId); + case "9C": + return softReset(serialHandle); + default: + break; + } + return false; + } + + + @Override + public boolean interruptStart(String deviceIp) { + + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.interruptStart(monipoiInfo.getId() + ""); + } + return false; + } + + @Override + public boolean alarmOperate(String command) { + List deviceCommonList = DeviceCommom.deviceCommonList; + switch (command) { + //关闭告警 + case "0": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 3); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + //打开告警 + case "1": + for (DeviceInfo deviceInfo : deviceCommonList) { + MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { + alarmControl(deviceInfo.getSerialHandle(), 2); + } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); + } + }); + } + } + return true; + } + return false; + } + + /** + * 不带速度的设备控制,调用sdk接口 + * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 + * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 + */ + @Override + public boolean control(Integer userId, String command, Integer isStop) { + logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); + int iPTZCommand = -1; + switch (command) { + case "clean": + iPTZCommand = HCNetSDK.WIPER_PWRON; + break; + case "zoomIn": + iPTZCommand = HCNetSDK.ZOOM_IN; + break; + case "zoomOut": + iPTZCommand = HCNetSDK.ZOOM_OUT; + break; + default: + break; + } + if (iPTZCommand <= -1) { + return false; + } + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + stopSerialHandle(deviceInfo.getSerialHandle()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); + if (isStop == 1) { + serialHandle(deviceInfo.getUserId()); + try { + Thread.sleep(500); + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; + } + + /** + * PTZControlAll 云台控制函数 + * + * @param userId 用户id + * @param iPTZCommand PTZ控制命令 + * @param iStop 开始或是停止操作 + * @param iSpeed 速度 + * @return + */ + private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { + if (userId.intValue() >= 0) { + boolean ret; + if (iSpeed >= 1) { + // 有速度的ptz + //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); + ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); + } else { + //速度为默认时 + //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); + ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); + } + return ret; + } else { + return false; + } + } + + /** + * 预置点管理(新增、删除、转到) + */ + @Override + public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + // 巡航路径固定为1,只有一条路径 + + int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; + boolean res = false; + + switch (command) { + case "presetAdd": + res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetEdit": + res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + case "presetDel": + res = presetDelete(userId, preset, cruiseRoute); + break; + case "toPreset": + res = toPreset(userId, preset, cruiseRoute); + break; + case "presetInsert": + res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + + @Override + public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { + boolean res = false; + + switch (command) { + case "cruiseEdit": + res = cruiseEdit(cruiseName, deviceIp, cruiseValue); + break; + case "cruiseDelete": + res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); + break; + default: + break; + } + +// serialHandle((long)userId); + return res; + } + + private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); + } + + + private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); + BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + //先停止巡航 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getDeviceType())) { + sendStopCommand(serialHandle); + } else { + stopCruise(userId); + } + + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + //先删除解码板上的预置点 + Thread.sleep(300); + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + } + + return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); + } + + /** + * 添加预置点:添加预置点 并 添加巡航路线 + */ + private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double + pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); + if (ObjectUtil.isEmpty(lineNum)) { + lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); + lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; + } + cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; + //廊坊设备 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isNotEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; + if (presetIndex.equals(presets[0])) { + presetIndex = presets[presets.length - 1] + 1; + } + if (presetIndex > cruiseRoute * 200) return false; + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (setPreset(serialHandle, presetIndex)) { + Thread.sleep(300); +// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 +// if (ObjectUtil.isEmpty(presetIndex)) { + Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); + presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; // } -// return true; -// //打开告警 -// case "1": -// for (DeviceInfo deviceInfo : deviceCommonList) { -// MonitorBaseInfo busMonipoiInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType()) && deviceInfo.getSerialHandle() > -1) { -// alarmControl(deviceInfo.getSerialHandle(), 2); -// } else if (DeviceTypeEnum.SELF_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(busMonipoiInfo.getMonitorId() + ""); -// } -// }); -// } + // 默认停留时间 + if (ObjectUtil.isEmpty(stopTime)) { + stopTime = Integer.valueOf(defaultStoptime); + } + //先停止 + stopCruise(userId); + + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); + } + } + return false; + } + + + /** + * 插入预置点 + */ + private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备 + if (baseInfo != null) { + + // 默认预置点编号 + if (ObjectUtil.isNotEmpty(presetIndex)) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), + cruiseRoute, presetIndex); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + //先删除云台预置点,所有的预置点往后推移 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //先停止 + sendStopCommand(serialHandle); + busObserpoiInfoList.forEach(busObserpoiInfo -> { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); + }); + } else { + //天讯通和奥瑞德停止巡航 + stopCruise(userId); + } + //删除数据库保存预置点信息 + obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + //添加预置点 + busObserpoiInfoList.forEach(busObserpoiInfo -> { + //过滤掉特殊预置点号 + int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; + //然后添加云台预置点 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), + busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + } else { + obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), + busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), + busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); + } + }); + } + + + //插入新建的预置点 + int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; + + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + if (setPreset(serialHandle, preset)) { + try { + Thread.sleep(300); + paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + return flag; + } + } + + return false; + } + + /** + * 编辑预置点 + */ + private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, + Double direction, Double pitch, Integer speed, Integer stopTime, + Integer alarmValue, String presetName, String cruiseName) { + boolean flag = false; + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + // 默认预置点编号 + try { + //给解码板设置预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + Thread.sleep(300); + flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); + } catch (Exception e) { + e.printStackTrace(); + flag = false; + } + if (!flag) return false; + } + } + return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, + cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); + } + + /** + * 删除预置点 + */ + private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { + + //给解码板删除预置位 + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + if (!deletePreset(serialHandle, presetIndex)) { + return false; + } + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //先停止 + stopCruise(userId); + return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); + } + return false; + } + + /** + * 转到预置点 + */ + private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { + + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //廊坊设备新指令 + if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(500); + return sendPreset(serialHandle, presetIndex); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + + } else { + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); + //先停止 + stopCruise(userId); + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + } + return false; + } + } + + /** + * 将预置点添加到巡航路线(已废弃) + */ + private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { + // 2.1 将预置点加入巡航序列 + boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + if (add) { + // 2.2 设置巡航点停顿时间 + boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); + if (dwell) { + // 2.3 设置巡航速度 + boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); + return sp; + } + } + return false; + } + + /** + * 从巡航路线中删除预置点(已废弃) + * sdk中的接口,从路线中删除一个预置点后,线路会失效 + * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 + */ + private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { + // 1.1 将预置点从巡航序列中删除 + boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); + // 1.2 查询巡航路径中的预置点 + if (delete) { + HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); + if (ObjectUtil.isNotEmpty(firstPoints)) { + // 1.3 转到其中一个预置点 + boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); + // 1.4 再次设置该预置点 + if (toPoint) { + try { + Thread.sleep(3 * 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); + } + } else { + // 巡航路径中没有其他预置点,则返回true + return true; + } + } + return false; + } + + /** + * 开启或停止自动巡航 + */ + @Override + public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { + boolean res = false; + Long serialHandle = serialHandle(Long.valueOf(userId)); + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + + switch (command) { + case "start": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); + + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + try { + //设置复位周期 + autoReset(serialHandle, presetInterval); + Thread.sleep(300); + //开始巡航调用指令 + res = sendPreset(serialHandle, 70); + Thread.sleep(300); + res = sendPreset(serialHandle, cruiseRoute); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } else { + res = startCruise(userId, cruiseRoute, interval); + } + break; + case "stop": +// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); + //廊坊新指令设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + res = sendStopCommand(serialHandle); + } else { + res = stopCruise(userId); + } + break; + default: + break; + } + return res; + } + + /** + * 开启自动巡航,新增对应的巡航线程 + */ + private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { + return false; + } + + // 如果设备已启动自动巡航,不能再次启动 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + return false; + } + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); + + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); + //巡航线程 + AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); + Thread cruiseThread = new Thread(task); + TaskCommon.threadMap.put(deviceInfo.getUserId(), task); + cruiseThread.start(); + //复位线程 + // 如果设备已启动复位,不能再次启动 + AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { + return false; + } + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { + AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? + delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getDeviceType(), this); + TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); + Thread resetTask = new Thread(cruiseResertTask); + resetTask.start(); + } + return true; + } + + private List getDefaultCruisePoints() { + List defaultPoints = new ArrayList<>(); + double pitch = -90; + while (pitch <= 90) { + defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); + defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); + pitch += 5; + } + return defaultPoints; + } + + /** + * 停止自动巡航,将对应task的退出标记设为true,退出线程 + */ + private boolean stopCruise(int userId) { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { + AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); + if (task != null) { + task.exit = true; + } + AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); + if (resertTask != null) { + resertTask.exit = true; + } + return true; + } + return false; + } + + /** + * 获取sdk错误码 + */ + @Override + public int getLastError() { + return hCNetSDK.NET_DVR_GetLastError(); + } + + /** + * 查询当前水平、垂直角度 + * 水平查询指令:指令格式:FF 01 00 51 00 00 52 + * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 + */ + @Override + public boolean getPosition(Long userId) { + Long serialHandle = serialHandle(userId); + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + } + + /** + * 设置角度:水平角度控制 + 垂直角度控制 + * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 + * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 + */ +// int i= 0; + @Override + public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { + + //与采集浓度指令错开 + //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms + if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { + try { + Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms + else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { + try { + Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; + int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; + int vData1, vData2; + if (verticalAngle < 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; + int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; + + Pointer horizontalPointer = intArrayToPointer(horizontalCommand); + Pointer verticalPointer = intArrayToPointer(verticalCommand); + logger.info("serical send horizon " + horizontalAngle); + boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); + try { + Thread.sleep(30); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("serical send vertical " + verticalAngle); + boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + return hres & vres; + + } + + + /** + * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM + * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 + * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 + * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 + */ + @Override + public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { + Long serialHandle = serialHandle(userId); + int hData1 = (int) (horizontalAngle * 100 / 0x100); + int hData2 = (int) (horizontalAngle * 100 % 0x100); + int vData1, vData2; + if (verticalAngle <= 0) { + vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); + vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); + } else { + vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); + vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); + } + int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; + int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; +// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; + Pointer verticalPointer = intArrayToPointer(Command); + logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); + return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); + + } + + + /** + * int数组转为Pointer + */ + private Pointer intArrayToPointer(int[] arr) { + Pointer pointer = new Memory(arr.length); + for (int i = 0; i < arr.length; i++) { + pointer.setByte(i, (byte) arr[i]); + } + return pointer; + } + + + /** + * 透明通道数据回调函数 + */ + public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { + @Override + public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { + // 如果小于4字节,为无用数据 + if (dwBufSize < 4) { + return; + } + + // 读取回传数据 + byte[] res = new byte[dwBufSize]; + char[] chars = new char[dwBufSize]; + int[] ires = new int[dwBufSize]; + for (int i = 0; i < dwBufSize; i++) { + res[i] = pRecvDataBuffer.getByte(i); + if (res[i] < 0) { + ires[i] = res[i] + 256; + } else { + ires[i] = res[i]; + } + chars[i] = (char) res[i]; + } + + // 查询对应的设备信息,查询不到直接退出 + DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); + if (ObjectUtil.isEmpty(deviceInfo)) { + return; + } + if (dwBufSize > 10) { + // 甲烷数据 + handleGasData(deviceInfo, String.valueOf(chars)); + } else { + int flag = ires[3]; + if (flag == 0x93) { + // 云台节点地址配置add 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x97) { + // 云台复位配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); + } else if (flag == 0x94) { + // 云台风险点角度配置 应答 + logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); + } else { + logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); + } +// if (flag == 0x59) { +// // 水平角度 +// handleHorizontalAngle(deviceInfo, ires); // } -// return true; -// } -// return false; -// } -// -// /** -// * 不带速度的设备控制,调用sdk接口 -// * 通用控制指令与透明通道不能同时使用,因此在开始控制前断开透明通道,在结束控制后开启透明通道 -// * 开启或结束透明通道后增加500ms延时,防止透明通道还没有完全开启或结束,导致通用控制失效 -// */ -// @Override -// public boolean control(Integer userId, String command, Integer isStop) { -// logger.info("device control: userId = " + userId + " command = " + command + " isStop =" + isStop); -// int iPTZCommand = -1; -// switch (command) { -// case "clean": -// iPTZCommand = HCNetSDK.WIPER_PWRON; -// break; -// case "zoomIn": -// iPTZCommand = HCNetSDK.ZOOM_IN; -// break; -// case "zoomOut": -// iPTZCommand = HCNetSDK.ZOOM_OUT; -// break; -// default: -// break; -// } -// if (iPTZCommand <= -1) { -// return false; -// } -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (isStop == 0 && ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// stopSerialHandle(deviceInfo.getSerialHandle()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// boolean res = PTZControlAll(new NativeLong(userId), iPTZCommand, isStop, 0); -// if (isStop == 1) { -// serialHandle(deviceInfo.getUserId()); -// try { -// Thread.sleep(500); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// return res; -// } -// -// /** -// * PTZControlAll 云台控制函数 -// * -// * @param userId 用户id -// * @param iPTZCommand PTZ控制命令 -// * @param iStop 开始或是停止操作 -// * @param iSpeed 速度 -// * @return -// */ -// private boolean PTZControlAll(NativeLong userId, int iPTZCommand, int iStop, int iSpeed) { -// if (userId.intValue() >= 0) { -// boolean ret; -// if (iSpeed >= 1) { -// // 有速度的ptz -// //ret = hCNetSDK.NET_DVR_PTZControlWithSpeed(lRealHandle, iPTZCommand, iStop, iSpeed); -// ret = hCNetSDK.NET_DVR_PTZControlWithSpeed_Other(userId, new NativeLong(1), iPTZCommand, iStop, iSpeed); -// } else { -// //速度为默认时 -// //ret = hCNetSDK.NET_DVR_PTZControl(lRealHandle, iPTZCommand, iStop); -// ret = hCNetSDK.NET_DVR_PTZControl_Other(userId, new NativeLong(1), iPTZCommand, iStop); -// } -// return ret; -// } else { -// return false; -// } -// } -// -// /** -// * 预置点管理(新增、删除、转到) -// */ -// @Override -// public boolean preset(Integer userId, String command, String presetIndex, Integer cruiseRoute, Double direction, Double pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// // 巡航路径固定为1,只有一条路径 -// -// int preset = ObjectUtil.isNotEmpty(presetIndex) ? Integer.valueOf(presetIndex) : 0; -// boolean res = false; -// -// switch (command) { -// case "presetAdd": -// res = presetAdd(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetEdit": -// res = presetEdit(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// case "presetDel": -// res = presetDelete(userId, preset, cruiseRoute); -// break; -// case "toPreset": -// res = toPreset(userId, preset, cruiseRoute); -// break; -// case "presetInsert": -// res = presetInsert(userId, preset, cruiseRoute, direction, pitch, speed, stopTime, alarmValue, presetName, cruiseName); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// -// @Override -// public boolean cruiseRoute(Integer userId, String command, Integer cruiseValue, String cruiseName, String deviceIp) { -// boolean res = false; -// -// switch (command) { -// case "cruiseEdit": -// res = cruiseEdit(cruiseName, deviceIp, cruiseValue); -// break; -// case "cruiseDelete": -// res = cruiseDelete(userId, deviceIp, cruiseName, cruiseValue); -// break; -// default: -// break; -// } -// -//// serialHandle((long)userId); -// return res; -// } -// -// private boolean cruiseEdit(String cruiseName, String deviceIp, Integer cruiseValue) { -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); -// return obserpoiInfoService.updateCruise(baseInfo.getMonitorId(), cruiseName, cruiseValue); -// } -// -// -// private boolean cruiseDelete(Integer userId, String deviceIp, String cruiseName, Integer cruiseValue) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectByMonitor(deviceIp, cruiseValue); -// BusMonipoiInfo busMonipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// //先停止巡航 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(busMonipoiInfo.getType())) { -// sendStopCommand(serialHandle); -// } else { -// stopCruise(userId); -// } -// -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// //先删除解码板上的预置点 -// Thread.sleep(300); -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// } catch (InterruptedException e) { -// e.printStackTrace(); +// if (flag == 0x5b) { +// // 垂直角度 +// handleVerticalAngle(deviceInfo, ires); // } -// }); -// } -// -// return obserpoiInfoService.deleteCruise(deviceIp, cruiseName, cruiseValue); -// } -// -// /** -// * 添加预置点:添加预置点 并 添加巡航路线 -// */ -// private boolean presetAdd(Integer userId, Integer presetIndex, Integer cruiseRoute, Double direction, Double -// pitch, Integer speed, Integer stopTime, Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// Integer lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), cruiseName); -// if (ObjectUtil.isEmpty(lineNum)) { -// lineNum = obserpoiInfoService.selectByMonitorByCruiseName(baseInfo.getMonitorId(), ""); -// lineNum = ObjectUtil.isNotEmpty(lineNum) ? lineNum + 1 : 1; -// } -// cruiseRoute = ObjectUtil.isNotEmpty(lineNum) ? lineNum : 1; -// //廊坊设备 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : (cruiseRoute - 1) * 200 + 1; -// if (presetIndex.equals(presets[0])) { -// presetIndex = presets[presets.length - 1] + 1; -// } -// if (presetIndex > cruiseRoute * 200) return false; -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (setPreset(serialHandle, presetIndex)) { -// Thread.sleep(300); -//// flag = stopTimeSet(serialHandle, presetIndex, stopTime, speed, alarmValue); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -//// if (ObjectUtil.isEmpty(presetIndex)) { -// Integer maxNum = obserpoiInfoService.selectMaxNum(baseInfo.getMonitorId(), cruiseRoute); -// presetIndex = ObjectUtil.isNotEmpty(maxNum) ? maxNum + 1 : 1; -//// } -// // 默认停留时间 -// if (ObjectUtil.isEmpty(stopTime)) { -// stopTime = Integer.valueOf(defaultStoptime); -// } -// //先停止 -// stopCruise(userId); -// -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, 5000, 30, presetName, cruiseName); -// } -// } -// return false; -// } -// -// -// /** -// * 插入预置点 -// */ -// private boolean presetInsert(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备 -// if (baseInfo != null) { -// -// // 默认预置点编号 -// if (ObjectUtil.isNotEmpty(presetIndex)) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// List busObserpoiInfoList = obserpoiInfoService.selectBeforesBySerialNum(deviceInfo.getDeviceIp(), -// cruiseRoute, presetIndex); -// if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { -// //先删除云台预置点,所有的预置点往后推移 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //先停止 -// sendStopCommand(serialHandle); -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// deletePreset(serialHandle, busObserpoiInfo.getSerialNum()); -// }); -// } else { -// //天讯通和奥瑞德停止巡航 -// stopCruise(userId); -// } -// //删除数据库保存预置点信息 -// obserpoiInfoService.deletePresetBySerials(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// //添加预置点 -// busObserpoiInfoList.forEach(busObserpoiInfo -> { -// //过滤掉特殊预置点号 -// int preset = (busObserpoiInfo.getSerialNum() + 1) == presets[0] ? presets[presets.length - 1] + 1 : busObserpoiInfo.getSerialNum() + 1; -// //然后添加云台预置点 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// stopTimeSet(serialHandle, preset, busObserpoiInfo.getStopTime(), -// busObserpoiInfo.getSpeed(), busObserpoiInfo.getAlarmValue()); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// } else { -// obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// busObserpoiInfo.getLineNum(), busObserpoiInfo.getDirection(), busObserpoiInfo.getPitch(), -// busObserpoiInfo.getStopTime(), busObserpoiInfo.getAlarmValue(), busObserpoiInfo.getSpeed(), -// busObserpoiInfo.getSerialName(), busObserpoiInfo.getLineName()); -// } -// }); -// } -// -// -// //插入新建的预置点 -// int preset = (presetIndex + 1) == presets[0] ? presets[presets.length - 1] + 1 : presetIndex + 1; -// -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// if (setPreset(serialHandle, preset)) { -// try { -// Thread.sleep(300); -// paramsSet(userId, serialHandle, preset, stopTime, speed, alarmValue); -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// flag = obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), preset, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// return flag; -// } -// } -// -// return false; -// } -// -// /** -// * 编辑预置点 -// */ -// private boolean presetEdit(Integer userId, Integer presetIndex, Integer cruiseRoute, -// Double direction, Double pitch, Integer speed, Integer stopTime, -// Integer alarmValue, String presetName, String cruiseName) { -// boolean flag = false; -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// // 默认预置点编号 -// try { -// //给解码板设置预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// Thread.sleep(300); -// flag = paramsSet(userId, serialHandle, presetIndex, stopTime, speed, alarmValue); -// } catch (Exception e) { -// e.printStackTrace(); -// flag = false; -// } -// if (!flag) return false; -// } -// } -// return obserpoiInfoService.addPresetByIp(deviceInfo.getDeviceIp(), presetIndex, -// cruiseRoute, direction, pitch, stopTime, alarmValue, speed, presetName, cruiseName); -// } -// -// /** -// * 删除预置点 -// */ -// private boolean presetDelete(int userId, int presetIndex, int cruiseRoute) { -// -// //给解码板删除预置位 -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// if (!deletePreset(serialHandle, presetIndex)) { -// return false; -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// } -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //先停止 -// stopCruise(userId); -// return obserpoiInfoService.deletePresetByIp(deviceInfo.getDeviceIp(), presetIndex, cruiseRoute); -// } -// return false; -// } -// -// /** -// * 转到预置点 -// */ -// private boolean toPreset(int userId, int presetIndex, int cruiseRoute) { -// -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //廊坊设备新指令 -// if (baseInfo != null && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(500); -// return sendPreset(serialHandle, presetIndex); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// return false; -// } -// -// } else { -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusObserpoiInfo obserpoiInfo = obserpoiInfoService.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, cruiseRoute); -// //先停止 -// stopCruise(userId); -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// return this.setPosition(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// return this.setPositionNew(deviceInfo.getUserId(), obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// } -// return false; -// } -// } -// -// /** -// * 将预置点添加到巡航路线(已废弃) -// */ -// private boolean addPresetToCruise(int realHandle, int presetIndex, int cruiseRoute, int speed, int stopTime) { -// // 2.1 将预置点加入巡航序列 -// boolean add = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.FILL_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// if (add) { -// // 2.2 设置巡航点停顿时间 -// boolean dwell = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_DWELL, (byte) cruiseRoute, (byte) presetIndex, (short) stopTime); -// if (dwell) { -// // 2.3 设置巡航速度 -// boolean sp = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.SET_SEQ_SPEED, (byte) cruiseRoute, (byte) presetIndex, (short) speed); -// return sp; -// } -// } -// return false; -// } -// -// /** -// * 从巡航路线中删除预置点(已废弃) -// * sdk中的接口,从路线中删除一个预置点后,线路会失效 -// * 所以删除后先转到当前存在的第一个预置点,并再次设置该预置点 -// */ -// private boolean deletePresetFromCruise(int userId, int realHandle, int presetIndex, int cruiseRoute) { -// // 1.1 将预置点从巡航序列中删除 -// boolean delete = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.CLE_PRE_SEQ, (byte) cruiseRoute, (byte) presetIndex, (short) presetIndex); -// // 1.2 查询巡航路径中的预置点 -// if (delete) { -// HCNetSDK.NET_DVR_CRUISE_POINT firstPoints = getFirstPoints(userId); -// if (ObjectUtil.isNotEmpty(firstPoints)) { -// // 1.3 转到其中一个预置点 -// boolean toPoint = toPreset(realHandle, firstPoints.PresetNum, cruiseRoute); -// // 1.4 再次设置该预置点 -// if (toPoint) { -// try { -// Thread.sleep(3 * 1000); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return addPresetToCruise(realHandle, firstPoints.PresetNum, 1, firstPoints.Speed, firstPoints.Dwell); -// } -// } else { -// // 巡航路径中没有其他预置点,则返回true -// return true; -// } -// } -// return false; -// } -// -// /** -// * 开启或停止自动巡航 -// */ -// @Override -// public boolean cruise(Integer userId, String command, Integer cruiseRoute, Integer interval) { -// boolean res = false; -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// -// switch (command) { -// case "start": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.RUN_SEQ, (byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// try { -// //设置复位周期 -// autoReset(serialHandle, presetInterval); -// Thread.sleep(300); -// //开始巡航调用指令 -// res = sendPreset(serialHandle, 70); -// Thread.sleep(300); -// res = sendPreset(serialHandle, cruiseRoute); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } else { -// res = startCruise(userId, cruiseRoute, interval); -// } -// break; -// case "stop": -//// res = hCNetSDK.NET_DVR_PTZCruise(new NativeLong(realHandle), HCNetSDK.STOP_SEQ,(byte) cruiseRoute.intValue(),(byte)0,(byte)0); -// //廊坊新指令设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// res = sendStopCommand(serialHandle); -// } else { -// res = stopCruise(userId); -// } -// break; -// default: -// break; -// } -// return res; -// } -// -// /** -// * 开启自动巡航,新增对应的巡航线程 -// */ -// private boolean startCruise(int userId, Integer cruiseRoute, Integer interval) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isEmpty(deviceInfo) || ObjectUtil.isEmpty(deviceInfo.getSerialHandle()) || deviceInfo.getSerialHandle() < 0) { -// return false; -// } -// -// // 如果设备已启动自动巡航,不能再次启动 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// return false; -// } -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceInfo.getDeviceIp(), cruiseRoute); -// -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// monipoiInfoService.updateBusMonipoiInfo(deviceInfo.getDeviceIp(), cruiseRoute); -// //巡航线程 -// AutoCruiseTask task = new AutoCruiseTask(obserpoiInfos, deviceInfo.getDeviceIp(), deviceInfo.getUserId(), this, webSocket, ObjectUtil.isNotEmpty(baseInfo) && DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType()) ? DeviceTypeEnum.SELF_TYPE.getCode() : DeviceTypeEnum.ARD_TYPE.getCode(), alarmRecordService, interval, ObjectUtil.isNotEmpty(baseInfo) ? baseInfo.getMonitorName() : ""); -// Thread cruiseThread = new Thread(task); -// TaskCommon.threadMap.put(deviceInfo.getUserId(), task); -// cruiseThread.start(); -// //复位线程 -// // 如果设备已启动复位,不能再次启动 -// AutoCruiseResertTask checkResetTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (ObjectUtil.isNotEmpty(checkResetTask) && checkResetTask.exit == false) { -// return false; -// } -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo) && ObjectUtil.isNotEmpty(monipoiInfo.getPresetInterval())) { -// AutoCruiseResertTask cruiseResertTask = new AutoCruiseResertTask(deviceInfo.getDeviceIp(), cruiseRoute, null == monipoiInfo.getPresetInterval() ? delayTime : monipoiInfo.getPresetInterval(), monipoiInfo.getType(), this); -// TaskCommon.threadResertMap.put(deviceInfo.getUserId(), cruiseResertTask); -// Thread resetTask = new Thread(cruiseResertTask); -// resetTask.start(); -// } -// return true; -// } -// -// private List getDefaultCruisePoints() { -// List defaultPoints = new ArrayList<>(); -// double pitch = -90; -// while (pitch <= 90) { -// defaultPoints.add(new BusObserpoiInfo(0.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(180.0, pitch, 0)); -// defaultPoints.add(new BusObserpoiInfo(360.0, pitch, 0)); -// pitch += 5; -// } -// return defaultPoints; -// } -// -// /** -// * 停止自动巡航,将对应task的退出标记设为true,退出线程 -// */ -// private boolean stopCruise(int userId) { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getSerialHandle()) && deviceInfo.getSerialHandle() >= 0) { -// AutoCruiseTask task = TaskCommon.threadMap.get(deviceInfo.getUserId()); -// if (task != null) { -// task.exit = true; -// } -// AutoCruiseResertTask resertTask = TaskCommon.threadResertMap.get(deviceInfo.getUserId()); -// if (resertTask != null) { -// resertTask.exit = true; -// } -// return true; -// } -// return false; -// } -// -// /** -// * 获取sdk错误码 -// */ -// @Override -// public int getLastError() { -// return hCNetSDK.NET_DVR_GetLastError(); -// } -// -// /** -// * 查询当前水平、垂直角度 -// * 水平查询指令:指令格式:FF 01 00 51 00 00 52 -// * 垂直查询指令:指令格式:FF 01 00 53 00 00 54 -// */ -// @Override -// public boolean getPosition(Long userId) { -// Long serialHandle = serialHandle(userId); -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x51, 0x00, 0x00, 0x52}; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x53, 0x00, 0x00, 0x54}; -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// } -// -// /** -// * 设置角度:水平角度控制 + 垂直角度控制 -// * 水平绝对角度控制,指令格式:FF ADD 00 4B DATA1 DATA2 SUM 其中(DATA1<<8) + DATA2=角度*100 -// * 垂直绝对角度控制,指令格式:FF ADD 00 4D DATA1 DATA2 SUM,若角度为负,(DATA1<<8) + DATA2=角度*100;若角度为正,(DATA1<<8) + DATA2=36000-角度*100。 -// */ -//// int i= 0; -// @Override -// public boolean setPosition(Long userId, Double horizontalAngle, Double verticalAngle) { -// -// //与采集浓度指令错开 -// //若发送采集指令后控制指令发生在300ms内,则把控制指令延迟至采集指令后300ms -// if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() < 300) { -// try { -// Thread.sleep(305 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } //若发送采集指令后控制指令发生在900-10000ms内,则把控制指令延迟至下一个采集指令后300ms -// else if (ObjectUtil.isNotEmpty(this.getTimestampCollcect()) && this.getTimestampCollcect() > 0 && System.currentTimeMillis() - this.getTimestampCollcect() > 900 && System.currentTimeMillis() - this.getTimestampCollcect() <= 1000) { -// try { -// Thread.sleep(1300 - (System.currentTimeMillis() - this.getTimestampCollcect())); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int hSum = (0x01 + 0x49 + hData1 + hData2) % 0x100; -// int[] horizontalCommand = {0xff, 0x01, 0x00, 0x49, hData1, hData2, hSum}; -// int vData1, vData2; -// if (verticalAngle < 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x4a + vData1 + vData2) % 0x100; -// int[] verticalCommand = {0xff, 0x01, 0x00, 0x4a, vData1, vData2, vSum}; -// -// Pointer horizontalPointer = intArrayToPointer(horizontalCommand); -// Pointer verticalPointer = intArrayToPointer(verticalCommand); -// logger.info("serical send horizon " + horizontalAngle); -// boolean hres = serialSend(serialHandle, horizontalPointer, (int) ((Memory) horizontalPointer).getSize()); -// try { -// Thread.sleep(30); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// logger.info("serical send vertical " + verticalAngle); -// boolean vres = serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// return hres & vres; -// -// } -// -// -// /** -// * 指令格式:FF 01 00 4C DATA1 DATA2 DATA3 DATA4 SUM -// * 其中DATA1(高字节)DATA2(低字节)表示水平角度的100倍 -// * DATA3(高字节)DATA4(低字节)表示垂直角度的100倍 -// * 例如:FF 01 00 4C 00 00 00 00 4D,表示跳转的水平0度和垂直0度 -// */ -// @Override -// public boolean setPositionNew(Long userId, Double horizontalAngle, Double verticalAngle) { -// Long serialHandle = serialHandle(userId); -// int hData1 = (int) (horizontalAngle * 100 / 0x100); -// int hData2 = (int) (horizontalAngle * 100 % 0x100); -// int vData1, vData2; -// if (verticalAngle <= 0) { -// vData1 = (int) ((0 - verticalAngle) * 100 / 0x100); -// vData2 = (int) ((0 - verticalAngle) * 100 % 0x100); -// } else { -// vData1 = (int) ((36000 - verticalAngle * 100) / 0x100); -// vData2 = (int) ((36000 - verticalAngle * 100) % 0x100); -// } -// int vSum = (0x01 + 0x00 + 0x4c + hData1 + hData2 + vData1 + vData2) % 0x100; -// int[] Command = {0xff, 0x01, 0x00, 0x4c, hData1, hData2, vData1, vData2, vSum}; -//// int[] Command = {0xff, 0x01, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x4d}; -// Pointer verticalPointer = intArrayToPointer(Command); -// logger.info("serical send horizon " + horizontalAngle + "-->serical send vertical " + verticalAngle); -// return serialSend(serialHandle, verticalPointer, (int) ((Memory) verticalPointer).getSize()); -// -// } -// -// -// /** -// * int数组转为Pointer -// */ -// private Pointer intArrayToPointer(int[] arr) { -// Pointer pointer = new Memory(arr.length); -// for (int i = 0; i < arr.length; i++) { -// pointer.setByte(i, (byte) arr[i]); -// } -// return pointer; -// } -// -// -// /** -// * 透明通道数据回调函数 -// */ -// public class SerialDataCallBack implements HCNetSDK.FSerialDataCallBack { -// @Override -// public void invoke(NativeLong lSerialHandle, Pointer pRecvDataBuffer, int dwBufSize, int dwUser) { -// // 如果小于4字节,为无用数据 -// if (dwBufSize < 4) { -// return; -// } -// -// // 读取回传数据 -// byte[] res = new byte[dwBufSize]; -// char[] chars = new char[dwBufSize]; -// int[] ires = new int[dwBufSize]; -// for (int i = 0; i < dwBufSize; i++) { -// res[i] = pRecvDataBuffer.getByte(i); -// if (res[i] < 0) { -// ires[i] = res[i] + 256; -// } else { -// ires[i] = res[i]; -// } -// chars[i] = (char) res[i]; -// } -// -// // 查询对应的设备信息,查询不到直接退出 -// DeviceInfo deviceInfo = DeviceCommom.selectBySerialHandle(lSerialHandle.longValue()); -// if (ObjectUtil.isEmpty(deviceInfo)) { -// return; -// } -// if (dwBufSize > 10) { -// // 甲烷数据 -// handleGasData(deviceInfo, String.valueOf(chars)); -// } else { -// int flag = ires[3]; -// if (flag == 0x93) { -// // 云台节点地址配置add 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device config 93-->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x97) { -// // 云台复位配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device reset 97--->").concat(String.valueOf(ires[4]))); -// } else if (flag == 0x94) { -// // 云台风险点角度配置 应答 -// logger.info(deviceInfo.getDeviceIp().concat(" get device angle 94--->").concat(String.valueOf(ires[4]))); -// } else { -// logger.info(deviceInfo.getDeviceIp().concat(" get device msg--->").concat(Arrays.toString(ires))); -// } -//// if (flag == 0x59) { -//// // 水平角度 -//// handleHorizontalAngle(deviceInfo, ires); -//// } -//// if (flag == 0x5b) { -//// // 垂直角度 -//// handleVerticalAngle(deviceInfo, ires); -//// } -// } -// } -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngleFromGasData(DeviceInfo deviceInfo, Double horizontalAngle) { -// -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngleFromGasData(DeviceInfo deviceInfo, Double verticalAngle) { -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { -//// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("verticalAngle", pitch); -// msg.put("horizontal", direction); -// msg.put("gasData", gas); -// msg.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss")); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// /** -// * 处理水平角度查询数据 -// */ -// private void handleHorizontalAngle(DeviceInfo deviceInfo, int[] data) { -// int pmsb = (int) data[4]; -// int plsb = (int) data[5]; -// double horizontalAngle = (pmsb * 256 + plsb) / 100.0; -// logger.info(deviceInfo.getDeviceIp().concat(" get horizontal angle").concat(String.valueOf(horizontalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "horizontalAngle"); -// msg.put("value", horizontalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// -// } -// -// -// /** -// * 处理垂直角度返回数据 -// */ -// private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { -// int tmsb = (int) data[4]; -// int tlsb = (int) data[5]; -// int tData = tmsb * 256 + tlsb; -// double verticalAngle; -// if (tData > 18000) { -// verticalAngle = (36000 - tData) / 100.0; -// } else if (tData < 18000) { -// verticalAngle = (0 - tData) / 100.0; -// } else { -// verticalAngle = tData / 100.0; -// } -// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", deviceInfo.getDeviceIp()); -// msg.put("userId", deviceInfo.getUserId()); -// msg.put("type", "verticalAngle"); -// msg.put("value", verticalAngle); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// /** -// * 处理甲烷浓度返回数据 -// */ -// @Transactional(rollbackFor = Exception.class) -// public void handleGasData(DeviceInfo deviceInfo, String gasData) { -// String[] data = gasData.split(","); -// if (!"005".equals(data[1])) { -// return; -// } -//// logger.info(deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// System.out.println(new Date()+":"+deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); -// if (data.length < 8) { -// return; -// } -// Double concentration = Double.valueOf(data[2]); -// double direction = Integer.parseInt(data[3]) / 100.0; -// double pitch = Integer.parseInt(data[4]) / 100.0; -// int alarmFlag = Integer.parseInt(data[5]); -// double alarmThreshold = Double.valueOf(data[6]); -// if (pitch > 180) { -// pitch = 360 - pitch; -// } else if (pitch < 180) { -// pitch = 0 - pitch; -// } -// -// direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); -// try { -// handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// final double direction1 = direction; -// final double pitch1 = pitch; -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// -// MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { -// try { -// -// //自带巡检设备 -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); -// insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); -// } else { -// -// AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); -//// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); -// DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); -// //存缓存,根据光照强度判断有无遮挡报警 -//// cacheStrength.add(deviceInfo.getDeviceIp(), processHidden(monitorBaseInfo, direction, pitch, Double.parseDouble(data[6])), 60 * 1000); -// -// } -// } catch (Exception e) { -// logger.error(e.getMessage()); -// } -// -// } -// } -// }); -// -// } -// -// public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setPitch(pitch); -// dataGasEs.setDirection(direction); -// dataGasEs.setConcentration(strength); -// return dataGasEs; -// } -// -// /** -// * 甲烷数据保存mysql -// */ -// private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch) { -// DataGas dataGas = new DataGas(); -// dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); -// dataGas.setConcentration(concentration); -// dataGas.setDircetion(direction); -// dataGas.setPitch(pitch); -// dataGas.setLogtime(new Date()); -// dataGasService.insert(dataGas); -// return dataGas; -// } -// -// /** -// * 甲烷数据保存es -// */ -// private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, -// double pitch, Double threshold) throws IOException { -// DataGasEs dataGasEs = new DataGasEs(); -// dataGasEs.setStationId(monitorBaseInfo.getStationId()); -// dataGasEs.setStationName(monitorBaseInfo.getStationName()); -// dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); -// dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); -// dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); -// dataGasEs.setDirection(direction); -// dataGasEs.setPitch(pitch); -// dataGasEs.setConcentration(concentration); -// dataGasEs.setLogTime(DateUtil.getTime()); -// dataGasEs.setThreshold(threshold); -// dataGasService.insertDataGasEs(dataGasEs); -// return dataGasEs; -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, -// boolean alarmFlag) { -// // 判断报警、消警 -// if (alarmFlag) { -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// } -// } -// -// -// /** -// * 生成报警(自动消警) -// */ -// private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { -// // 判断报警、消警 -// //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); -// -// if (threshold != null && dataGas.getConcentration() > threshold) { -// boolean resumeFlag = false; -// // 报警,注意消警时限 -// EntityWrapper query = new EntityWrapper<>(); -// query.eq("MONITOR_ID", dataGas.getMonitorId()); -// query.eq("ALARM_STATUS", "1"); -// query.eq("ALARM_DIRECTION", dataGas.getDirection()); -// query.eq("ALARM_PITCH", dataGas.getPitch()); -// query.isNotNull("RESUME_TIME"); -// List resumeList = alarmRecordService.selectList(query); -// -// for (AlarmRecord alarmRecord : resumeList) { -// long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); -// if (min < alarmRecord.getResumeTime()) { -// resumeFlag = true; -// break; -// } -// } -// // 不在消警时限内 -// if (!resumeFlag) { -// //同一位置告警且不超过10s不推送到前端 -//// EntityWrapper ew = new EntityWrapper<>(); -//// ew.eq("MONITOR_ID", dataGas.getMonitorId()); -//// ew.eq("ALARM_STATUS", "0"); -//// ew.eq("ALARM_DIRECTION", dataGas.getDirection()); -//// ew.eq("ALARM_PITCH", dataGas.getPitch()); -//// ew.orderBy("ALARM_TIME", false); -//// AlarmRecord alarmRecordLast = this.alarmRecordService.selectOne(ew); -// -// // 消除同一角度已有报警 -// alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// // 插入新报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("甲烷浓度超限"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(threshold); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// alarmRecordService.insert(alarmRecord); -// //推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "gasAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// //增加门禁报警控制,只针对天讯通设备 -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } else { -// // 自动消警(同一角度) -// int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); -// if (count > 0) { -// JSONObject msg = new JSONObject(); -// msg.put("type", "cancelAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorBaseInfo.getMonitorName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { -// threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { -// @Override -// public void run() { -// CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); -// } -// }); -// } -// } -// } -// -// public void insertStrengthAlarm(SoftReference objectSoftReference, String monitorName, DataGasEs dataGas) { -// -// //比较2次的光照强度是否超过400 -// DataGasEs dataGasEs = (DataGasEs) objectSoftReference.get(); -// if (!(dataGasEs.getPitch().equals(dataGas.getPitch()) && dataGasEs.getDirection().equals(dataGas.getDirection()))) { -// List alarmRecords = alarmRecordService.getListBycode(dataGas.getDevcode(), "2"); -// if (Math.abs(dataGas.getConcentration() - dataGasEs.getConcentration()) < Double.valueOf(alarmvalue)) { -// if (alarmRecords != null && alarmRecords.size() > 0) return; -// // 新增报警 -// AlarmRecord alarmRecord = new AlarmRecord(); -// alarmRecord.setMonitorId(dataGas.getMonitorId()); -// alarmRecord.setDeviceCode(dataGas.getDevcode()); -// alarmRecord.setAlarmContent("遮挡报警"); -// alarmRecord.setAlarmType("2"); -// alarmRecord.setAlarmValue(dataGas.getConcentration()); -// alarmRecord.setAlarmThresh(Double.valueOf(alarmvalue)); -// alarmRecord.setAlarmTime(new Date()); -// alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); -// alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); -// alarmRecord.setAlarmStatus("0"); -// // 插入新报警 -// alarmRecordService.insert(alarmRecord); -// // websocket 推送前端 -// JSONObject msg = new JSONObject(); -// msg.put("type", "strengthAlarm"); -// msg.put("monitorId", dataGas.getMonitorId()); -// msg.put("monitorName", monitorName); -// msg.put("concentration", alarmRecord.getAlarmValue()); -// msg.put("alarmDirection", alarmRecord.getAlarmDirection()); -// msg.put("alarmPitch", alarmRecord.getAlarmPitch()); -// msg.put("alarmId", alarmRecord.getId()); -// msg.put("alarmTime", DateUtil.getTime(alarmRecord.getAlarmTime())); -// webSocket.sendAllMessage(msg.toJSONString()); -// } else { -// //消警(遮挡) -// if (ObjectUtil.isNotEmpty(alarmRecords)) { -// for (AlarmRecord alarmRecord : alarmRecords) { -// alarmRecord.setAlarmStatus("1"); -// } -// alarmRecordService.updateBatchById(alarmRecords); -// } -// } -// } -// } -// -// -// /** -// * 查询云台预置点(从设备sdk查询) -// */ -// public int getPoints(Long userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// return points.length; -// } -// -// /** -// * 查询云台第一个有效的预置点 -// */ -// private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { -// int cruiseRoute = 1; -// HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); -// hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); -// HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; -// if (points.length > 0) { -// for (int i = 0; i < points.length; i++) { -// if (points[i].Speed > 0) { -// return points[i]; -// } -// } -// } -// return null; -// } -// -// /** -// * 查询云台预置点(从数据库查询) -// */ -// @Override -// public List getPoints(String deviceIp, Integer cruiseRoute) { -// List points = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); -// }); -// return points; -// } -// -// @Override -// public List getLines(String deviceIp) { -// List lines = new ArrayList<>(); -// List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); -// obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); -// obserpoiInfos.forEach(busObserpoiInfo -> { -// lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); -// }); -// return lines; -// } -// -// @Override -// public boolean getDeviceConfig(Long userId) { -// Long serialHandle = serialHandle(Long.valueOf(userId)); -// setPreset(serialHandle, 79); -// sendPreset(serialHandle, 79); -// return false; -// } -// -// @Override -// public boolean setPresetCommand(Long userId, String command) { -// Long serialHandle = serialHandle(userId); -// -// try { -// //先停止 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// //兼容宇视通设备 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// if (ObjectUtil.isNotEmpty(baseInfo)) { -// if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// return softReset(serialHandle); -// } -// } -// } -// Thread.sleep(300); -// //停止巡航 -// stopCruise(userId.intValue()); -// Thread.sleep(300); -// if ("79".equals(command)) { -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { -// preset0(serialHandle); -// } -// } else if (command.indexOf("82") == 0) { -// String[] arr = command.split("A"); -// if (arr.length > 1) { -// try { -// int subPoint = Integer.parseInt(arr[1]); -// //启动82预置点 -// sendPreset(serialHandle, 82); -// //自启动预留30秒 -// Thread.sleep(300); -// //启动预置点操作 -// sendPreset(serialHandle, subPoint); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return false; -// } -// return true; -// } -// -// /** -// * 自研设备自检复位 -// */ -// public void preset1(Long serialHandle) { -// -// try { -// //设置79号复位预置点 -// setPreset(serialHandle, 79); -// Thread.sleep(300); -// //启动复位操作 -// sendPreset(serialHandle, 79); -// //自启动预留90秒 -// Thread.sleep(90 * 1000); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// -// /** -// * 外协设备自检复位 -// * 调用65预置位,再调用92预置位,是强制重启功能; -// */ -// public boolean preset0(Long serialHandle) { -// -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //启动复位操作 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //启动复位操作 -// flag = sendPreset(serialHandle, 92); -// //自启动预留30秒 -// Thread.sleep(30 * 1000); -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// flag = false; -// } -// return flag; -// } -// -// -// /** -// * 甲烷浓度全局阈值设置 -// * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; -// */ -// public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { -// -// -// try { -// //全局变量阈值存库 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// //只针对宇视通和奥瑞德设备下发至云台 -// if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getType()) || -// ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getType())) { -// //先停止巡航 -// if(sendStopCommand(serialHandle)){ -// Thread.sleep(300); -// }else { -// //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 -// sendStopCommand(serialHandle); -// Thread.sleep(300); -// } -// if(sendPreset(serialHandle, 68)){ -// Thread.sleep(300); -// //报警值除以100,设置预置点 -// sendPreset(serialHandle, value / 100); -// } -// } -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); -// //更新预置点阈值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); -// } -// } -// return true; -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean restart(Integer userId) { -// //toDo:用门禁控制器2通道控制断电重启 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// return CommDoorUtil.restart(monipoiInfo.getId() + ""); -// } -// } -// return false; -// } -// -// public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { -// -// try { -// stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); -// //若有局部阈值设置则全局值设置为空 -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// -// public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// patrolStopTimeSet(serialHandle, value); -// } -// //设置全局变量停留时间 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); -// //更新预置点停留时间值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //一键巡检速度设置 -// patrolSpeedSet(serialHandle, value); -// } -// //设置全局变量速度 -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); -// //更新预置点速度值 -// obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { -// -// try { -// DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); -// MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); -// //只针对宇视通设备 -// if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { -// //风险点局部扫描角度配置 -// riskPointAngleSet(serialHandle, value); -// } -// -// if (ObjectUtil.isNotEmpty(deviceInfo)) { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); -// } -// } -// return true; -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return false; -// } -// -// //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 -// public boolean allCruise(Long serialHandle) { -// boolean flag = false; -// try { -// //先停止巡航 -// if (sendStopCommand(serialHandle)) { -// Thread.sleep(300); -// //调用65号预置位 -// if (sendPreset(serialHandle, 65)) { -// Thread.sleep(300); -// //调用126号预置位 -// if (sendPreset(serialHandle, 126)) { -// Thread.sleep(300); -// //调用70号预置位 -// if (sendPreset(serialHandle, 70)) { -// Thread.sleep(300); -// //调用1号预置位 -// flag = sendPreset(serialHandle, 1); -// } -// } -// } -// } -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// return flag; -// } -// -// -// @Override -// public boolean preset(String deviceIp, Integer lineNum, String type) { -// Long userId = getUserIdByIp(deviceIp); -// if (ObjectUtil.isEmpty(userId) || userId < 0) { -// return false; -// } -// Long serialHandle = serialHandle(userId); -// //先停止 -// sendStopCommand(serialHandle); -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// //停止巡航 -// AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); -// boolean flagCruise = false; -// if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { -// stopCruise(userId.intValue()); -// flagCruise = true; -// } -// try { -// Thread.sleep(300); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { -// preset1(serialHandle); -// } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { -// preset0(serialHandle); -// } -// //自动启动巡航 -// if (ObjectUtil.isNotEmpty(lineNum)) { -// //若是复位导致的巡航停止,则重启 -// if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); -// } -// return true; -// } -// -// private Long getUserIdByIp(String deviceIp) { -// Long userId = null; -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { -// userId = deviceInfo.getUserId(); -// } else { -// BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); -// if (ObjectUtil.isNotEmpty(monipoiInfo)) { -// userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); -// } -// } -// return userId; -// } -//} + } + } + } + + private void handlegasDataFromGasData(DeviceInfo deviceInfo, Double gas, Double direction, Double pitch) { +// logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat(" get vertical angle-->").concat(String.valueOf(pitch)).concat("+ get horizontal angle-->").concat(String.valueOf(direction)).concat("+ get gas data-->").concat(String.valueOf(gas))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("verticalAngle", pitch); + msg.put("horizontal", direction); + msg.put("gasData", gas); + msg.put("time", DateUtil.formatDateTime(new Date())); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理垂直角度返回数据 + */ + private void handleVerticalAngle(DeviceInfo deviceInfo, int[] data) { + int tmsb = (int) data[4]; + int tlsb = (int) data[5]; + int tData = tmsb * 256 + tlsb; + double verticalAngle; + if (tData > 18000) { + verticalAngle = (36000 - tData) / 100.0; + } else if (tData < 18000) { + verticalAngle = (0 - tData) / 100.0; + } else { + verticalAngle = tData / 100.0; + } + logger.info(deviceInfo.getDeviceIp().concat(" get vertical angle").concat(String.valueOf(verticalAngle))); + JSONObject msg = new JSONObject(); + msg.put("deviceIp", deviceInfo.getDeviceIp()); + msg.put("userId", deviceInfo.getUserId()); + msg.put("type", "verticalAngle"); + msg.put("value", verticalAngle); + webSocket.sendAllMessage(msg.toJSONString()); + } + + /** + * 处理甲烷浓度返回数据 + */ + @Transactional(rollbackFor = Exception.class) + public void handleGasData(DeviceInfo deviceInfo, String gasData) { + String[] data = gasData.split(","); + if (!"005".equals(data[1])) { + return; + } + System.out.println(new Date() + ":" + deviceInfo.getDeviceIp().concat("获得甲烷数据:").concat(gasData)); + if (data.length < 8) { + return; + } + Double concentration = Double.valueOf(data[2]); + double direction = Integer.parseInt(data[3]) / 100.0; + double pitch = Integer.parseInt(data[4]) / 100.0; + int alarmFlag = Integer.parseInt(data[5]); + double alarmThreshold = Double.valueOf(data[6]); + if (pitch > 180) { + pitch = 360 - pitch; + } else if (pitch < 180) { + pitch = 0 - pitch; + } + + direction = new BigDecimal(direction).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + pitch = new BigDecimal(pitch).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); + try { + handlegasDataFromGasData(deviceInfo, concentration, direction, pitch); + } catch (Exception e) { + e.printStackTrace(); + } + final double direction1 = direction; + final double pitch1 = pitch; + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + + MonitorBaseInfo monitorBaseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monitorBaseInfo)) { + try { + + //自带巡检设备 + if (DeviceTypeEnum.XST_TYPE.getCode().equals(monitorBaseInfo.getType())) { + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, alarmThreshold); + insertGasAlarmProduct(monitorBaseInfo, dataGasEs, alarmThreshold, 1 == alarmFlag ? true : false); + } else { + + AlarmRule alarmRule = alarmRuleService.selectByMonitor(monitorBaseInfo.getMonitorId()); +// DataGas dataGas = insertDataGas(monitorBaseInfo,concentration,direction,pitch); + DataGasEs dataGasEs = insertDataGasEs(monitorBaseInfo, concentration, direction1, pitch1, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + insertGasAlarm(monitorBaseInfo, dataGasEs, ObjectUtil.isNotEmpty(alarmRule) ? alarmRule.getHigh() : null); + } + } catch (Exception e) { + logger.error(e.getMessage()); + } + + } + } + }); + + } + + public DataGasEs processHidden(MonitorBaseInfo monitorBaseInfo, double direction, double pitch, Double strength) { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setPitch(pitch); + dataGasEs.setDirection(direction); + dataGasEs.setConcentration(strength); + return dataGasEs; + } + + /** + * 甲烷数据保存mysql + */ + private DataGas insertDataGas(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch) { + DataGas dataGas = new DataGas(); + dataGas.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGas.setDeviceCode(monitorBaseInfo.getDevcode()); + dataGas.setConcentration(concentration); + dataGas.setDircetion(direction); + dataGas.setPitch(pitch); + dataGas.setLogtime(new Date()); + dataGasService.save(dataGas); + return dataGas; + } + + /** + * 甲烷数据保存es + */ + private DataGasEs insertDataGasEs(MonitorBaseInfo monitorBaseInfo, Double concentration, double direction, + double pitch, Double threshold) throws IOException { + DataGasEs dataGasEs = new DataGasEs(); + dataGasEs.setStationId(monitorBaseInfo.getStationId()); + dataGasEs.setStationName(monitorBaseInfo.getStationName()); + dataGasEs.setMonitorId(monitorBaseInfo.getMonitorId()); + dataGasEs.setMonitorName(monitorBaseInfo.getMonitorName()); + dataGasEs.setDevcode(monitorBaseInfo.getDevcode()); + dataGasEs.setDirection(direction); + dataGasEs.setPitch(pitch); + dataGasEs.setConcentration(concentration); + dataGasEs.setLogTime(DateUtil.formatDateTime(new Date())); + dataGasEs.setThreshold(threshold); + dataGasService.insertDataGasEs(dataGasEs); + return dataGasEs; + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarmProduct(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold, + boolean alarmFlag) { + // 判断报警、消警 + if (alarmFlag) { + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + } + } + + + /** + * 生成报警(自动消警) + */ + private void insertGasAlarm(MonitorBaseInfo monitorBaseInfo, DataGasEs dataGas, Double threshold) { + // 判断报警、消警 + //AlarmRule alarmRule = alarmRuleService.selectByMonitor(dataGas.getMonitorId()); + + if (threshold != null && dataGas.getConcentration() > threshold) { + boolean resumeFlag = false; + // 报警,注意消警时限 + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", dataGas.getMonitorId()); + query.eq("ALARM_STATUS", "1"); + query.eq("ALARM_DIRECTION", dataGas.getDirection()); + query.eq("ALARM_PITCH", dataGas.getPitch()); + query.isNotNull("RESUME_TIME"); + List resumeList = alarmRecordService.list(query); + + for (AlarmRecord alarmRecord : resumeList) { + long min = (System.currentTimeMillis() - alarmRecord.getCancelTime().getTime()) / (1000 * 60); + if (min < alarmRecord.getResumeTime()) { + resumeFlag = true; + break; + } + } + // 不在消警时限内 + if (!resumeFlag) { + + // 消除同一角度已有报警 + alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + // 插入新报警 + AlarmRecord alarmRecord = new AlarmRecord(); + alarmRecord.setMonitorId(dataGas.getMonitorId()); + alarmRecord.setDeviceCode(dataGas.getDevcode()); + alarmRecord.setAlarmContent("甲烷浓度超限"); + alarmRecord.setAlarmValue(dataGas.getConcentration()); + alarmRecord.setAlarmThresh(threshold); + alarmRecord.setAlarmTime(new Date()); + alarmRecord.setAlarmDirection(Double.valueOf(dataGas.getDirection())); + alarmRecord.setAlarmPitch(Double.valueOf(dataGas.getPitch())); + alarmRecord.setAlarmStatus("0"); + alarmRecordService.save(alarmRecord); + //推送前端 + JSONObject msg = new JSONObject(); + msg.put("type", "gasAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + msg.put("concentration", alarmRecord.getAlarmValue()); + msg.put("alarmDirection", alarmRecord.getAlarmDirection()); + msg.put("alarmPitch", alarmRecord.getAlarmPitch()); + msg.put("alarmId", alarmRecord.getId()); + msg.put("alarmTime", alarmRecord.getAlarmTime()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******sendwebSocketAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + //增加门禁报警控制,只针对天讯通设备 + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.controlPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } else { + // 自动消警(同一角度) + int count = alarmRecordService.clearByMonitor(dataGas.getMonitorId(), Double.valueOf(dataGas.getDirection()), Double.valueOf(dataGas.getPitch())); + if (count > 0) { + JSONObject msg = new JSONObject(); + msg.put("type", "cancelAlarm"); + msg.put("monitorId", dataGas.getMonitorId()); + msg.put("monitorName", monitorBaseInfo.getMonitorName()); + webSocket.sendAllMessage(msg.toJSONString()); + logger.info("*******webSocketcancelAlarmRecord,monitorid=" + dataGas.getMonitorId() + ",time:" + new Date()); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(monitorBaseInfo.getType())) { + threadPoolTaskExecutor.taskExecutor().execute(new Runnable() { + @Override + public void run() { + CommDoorUtil.cancelPTZ(monitorBaseInfo.getMonitorId() + ""); + } + }); + } + } + } + + + /** + * 查询云台预置点(从设备sdk查询) + */ + public int getPoints(Long userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + return points.length; + } + + /** + * 查询云台第一个有效的预置点 + */ + private HCNetSDK.NET_DVR_CRUISE_POINT getFirstPoints(int userId) { + int cruiseRoute = 1; + HCNetSDK.NET_DVR_CRUISE_RET ret = new HCNetSDK.NET_DVR_CRUISE_RET(); + hCNetSDK.NET_DVR_GetPTZCruise(new NativeLong(userId), new NativeLong(1), new NativeLong(cruiseRoute), ret); + HCNetSDK.NET_DVR_CRUISE_POINT[] points = ret.struCruisePoint; + if (points.length > 0) { + for (int i = 0; i < points.length; i++) { + if (points[i].Speed > 0) { + return points[i]; + } + } + } + return null; + } + + /** + * 查询云台预置点(从数据库查询) + */ + @Override + public List getPoints(String deviceIp, Integer cruiseRoute) { + List points = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp, cruiseRoute); + obserpoiInfos.forEach(busObserpoiInfo -> { + points.add(new SelectDTO(busObserpoiInfo.getSerialName(), busObserpoiInfo.getSerialNum() + "")); + }); + return points; + } + + @Override + public List getLines(String deviceIp) { + List lines = new ArrayList<>(); + List obserpoiInfos = obserpoiInfoService.selectByMonitor(deviceIp); + obserpoiInfos = obserpoiInfos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusObserpoiInfo::getLineNum))), ArrayList::new)); + obserpoiInfos.forEach(busObserpoiInfo -> { + lines.add(new SelectDTO(busObserpoiInfo.getLineName(), busObserpoiInfo.getLineNum() + "")); + }); + return lines; + } + + @Override + public boolean getDeviceConfig(Long userId) { + Long serialHandle = serialHandle(Long.valueOf(userId)); + setPreset(serialHandle, 79); + sendPreset(serialHandle, 79); + return false; + } + + @Override + public boolean setPresetCommand(Long userId, String command) { + Long serialHandle = serialHandle(userId); + + try { + //先停止 + sendStopCommand(serialHandle); + Thread.sleep(300); + //兼容宇视通设备 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId((long) userId); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + if (ObjectUtil.isNotEmpty(baseInfo)) { + if (DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + return softReset(serialHandle); + } + } + } + Thread.sleep(300); + //停止巡航 + stopCruise(userId.intValue()); + Thread.sleep(300); + if ("79".equals(command)) { + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(baseInfo.getType())) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(baseInfo.getType())) { + preset0(serialHandle); + } + } else if (command.indexOf("82") == 0) { + String[] arr = command.split("A"); + if (arr.length > 1) { + try { + int subPoint = Integer.parseInt(arr[1]); + //启动82预置点 + sendPreset(serialHandle, 82); + //自启动预留30秒 + Thread.sleep(300); + //启动预置点操作 + sendPreset(serialHandle, subPoint); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + /** + * 自研设备自检复位 + */ + public void preset1(Long serialHandle) { + + try { + //设置79号复位预置点 + setPreset(serialHandle, 79); + Thread.sleep(300); + //启动复位操作 + sendPreset(serialHandle, 79); + //自启动预留90秒 + Thread.sleep(90 * 1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + /** + * 外协设备自检复位 + * 调用65预置位,再调用92预置位,是强制重启功能; + */ + public boolean preset0(Long serialHandle) { + + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //启动复位操作 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //启动复位操作 + flag = sendPreset(serialHandle, 92); + //自启动预留30秒 + Thread.sleep(30 * 1000); + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + flag = false; + } + return flag; + } + + + /** + * 甲烷浓度全局阈值设置 + * 先调用68号预置位,value预置位 设置浓度等于这个预置位数值乘以100,比如设置浓度阈值为5000则先调用68号预置位,再调用50号预置位; + */ + public boolean setWholeAlarmValue(Integer userId, Long serialHandle, int value) { + + + try { + //全局变量阈值存库 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + //只针对宇视通和奥瑞德设备下发至云台 + if (ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.XST_TYPE.getCode().equals(monipoiInfo.getDeviceType()) || + ObjectUtil.isNotEmpty(monipoiInfo) && DeviceTypeEnum.ARD_TYPE.getCode().equals(monipoiInfo.getDeviceType())) { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + } else { + //若第一次未停止成功,发2次停止 保证设备已停止后设置预置 + sendStopCommand(serialHandle); + Thread.sleep(300); + } + if (sendPreset(serialHandle, 68)) { + Thread.sleep(300); + //报警值除以100,设置预置点 + sendPreset(serialHandle, value / 100); + } + } + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), Double.valueOf(value)); + //更新预置点阈值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, value, null); + } + } + return true; + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + + public boolean restart(Integer userId) { + //toDo:用门禁控制器2通道控制断电重启 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + return CommDoorUtil.restart(monipoiInfo.getId() + ""); + } + } + return false; + } + + public boolean paramsSet(Integer userId, Long serialHandle, int value, int stopTime, int speed, int alarmValue) { + + try { + stopTimeSet(serialHandle, value, stopTime, speed, alarmValue); + //若有局部阈值设置则全局值设置为空 + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + + public boolean patrolStopTimeSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + patrolStopTimeSet(serialHandle, value); + } + //设置全局变量停留时间 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, value, null, null); + //更新预置点停留时间值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), value, null, null); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean patrolSpeedSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //一键巡检速度设置 + patrolSpeedSet(serialHandle, value); + } + //设置全局变量速度 + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, value, null); + //更新预置点速度值 + obserpoiInfoService.updateGlobalValues(deviceInfo.getDeviceIp(), null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + public boolean riskPointAngleSetWhole(Integer userId, Long serialHandle, int value) { + + try { + DeviceInfo deviceInfo = DeviceCommom.selectByUserId(Long.valueOf(userId)); + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceInfo.getDeviceIp()); + //只针对宇视通设备 + if (null != baseInfo && DeviceTypeEnum.XST_TYPE.getCode().equals(baseInfo.getType())) { + //风险点局部扫描角度配置 + riskPointAngleSet(serialHandle, value); + } + + if (ObjectUtil.isNotEmpty(deviceInfo)) { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceInfo.getDeviceIp()); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + alarmRuleService.resetAlarmRule(monipoiInfo.getId(), null, null, null, value); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + //实现全部有效预置位一起巡航,需要调用一次快捷预置位命令组合“65+126”,然后调用“70+1”便可以将所有有效预置位从小到大依次循环巡航 + public boolean allCruise(Long serialHandle) { + boolean flag = false; + try { + //先停止巡航 + if (sendStopCommand(serialHandle)) { + Thread.sleep(300); + //调用65号预置位 + if (sendPreset(serialHandle, 65)) { + Thread.sleep(300); + //调用126号预置位 + if (sendPreset(serialHandle, 126)) { + Thread.sleep(300); + //调用70号预置位 + if (sendPreset(serialHandle, 70)) { + Thread.sleep(300); + //调用1号预置位 + flag = sendPreset(serialHandle, 1); + } + } + } + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + return flag; + } + + + @Override + public boolean preset(String deviceIp, Integer lineNum, String type) { + Long userId = getUserIdByIp(deviceIp); + if (ObjectUtil.isEmpty(userId) || userId < 0) { + return false; + } + Long serialHandle = serialHandle(userId); + //先停止 + sendStopCommand(serialHandle); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + //停止巡航 + AutoCruiseTask checkTask = TaskCommon.threadMap.get(userId); + boolean flagCruise = false; + if (ObjectUtil.isNotEmpty(checkTask) && checkTask.exit == false) { + stopCruise(userId.intValue()); + flagCruise = true; + } + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if (DeviceTypeEnum.SELF_TYPE.getCode().equals(type)) { + preset1(serialHandle); + } else if (DeviceTypeEnum.ARD_TYPE.getCode().equals(type)) { + preset0(serialHandle); + } + //自动启动巡航 + if (ObjectUtil.isNotEmpty(lineNum)) { + //若是复位导致的巡航停止,则重启 + if (flagCruise) cruise(userId.intValue(), "start", lineNum, 750); + } + return true; + } + + private Long getUserIdByIp(String deviceIp) { + Long userId = null; + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(deviceInfo) && ObjectUtil.isNotEmpty(deviceInfo.getUserId()) && deviceInfo.getUserId() > 0) { + userId = deviceInfo.getUserId(); + } else { + BusMonipoiInfo monipoiInfo = monipoiInfoService.selectByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(monipoiInfo)) { + userId = this.register(monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword(), deviceIp); + } + } + return userId; + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java index 9a53e1d..9201520 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/AutoCruiseTask.java @@ -1,244 +1,245 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.alibaba.fastjson.JSONObject; -//import com.casic.missiles.core.util.DateUtil; -//import com.casic.missiles.modular.system.model.BusObserpoiInfo; -//import com.casic.missiles.modular.system.service.IAlarmRecordService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.util.WebSocket; -//import org.springframework.stereotype.Component; -// -//import java.text.SimpleDateFormat; -//import java.util.Calendar; -//import java.util.Date; -//import java.util.GregorianCalendar; -//import java.util.List; -// -///** -// * 自动巡航线程 -// */ -//@Component -//public class AutoCruiseTask implements Runnable { -// -// /** -// * 线程退出标记 -// */ -// public volatile boolean exit = false; -// /** -// * 巡航点列表 -// */ -// private List pointList; -// /** -// * 设备登录ip -// */ -// private String deviceIp; -// /** -// * 设备登录id -// */ -// private Long userId; -// -// /** -// * 设备类型 -// */ -// private String type; -// -// /** -// * 设备控制service -// */ -// private IHCNetService ihcNetService; -// /** -// * -// */ -// private String monitorName; -// -// private Integer interval; -// private WebSocket webSocket; -// -// private IAlarmRecordService iAlarmRecordService; -// -// public AutoCruiseTask() { -// } -// -// public AutoCruiseTask(List pointList, String deviceIp, Long userId, -// IHCNetService ihcNetService, WebSocket webSocket, -// String type, IAlarmRecordService iAlarmRecordService, -// Integer interval, String monitorName) { -// this.pointList = pointList; -// this.deviceIp = deviceIp; -// this.userId = userId; -// this.ihcNetService = ihcNetService; -// this.webSocket = webSocket; -// this.type = type; -// this.iAlarmRecordService = iAlarmRecordService; -// this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; -// this.monitorName = monitorName; -// } -// -// /** -// * 自动巡航线程: -// * 1.查询巡航点 -// * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... -// */ -// @Override -// public void run() { -// -// -// while (!exit) { -// // 只要线程未中止,一直循环航线 -// for (int i = 0; i < pointList.size(); i++) { -// BusObserpoiInfo obserpoiInfo = pointList.get(i); -// // 前一个巡航点,用于计算云台旋转所需时间 -// BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); -// try { -// // 如果线程中止,不再转到下一个点 -// if (!exit) { -// boolean flag = false; -// if ("1".equals(type)) { -// flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } else { -// flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); -// } -// // 向前端推送当前预置点编号: -// if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { -// JSONObject msg = new JSONObject(); -// msg.put("deviceIp", this.deviceIp); -// msg.put("userId", this.userId); -// msg.put("type", "presetIndex"); -// msg.put("value", obserpoiInfo.getSerialNum()); -// msg.put("name", obserpoiInfo.getSerialName()); -// webSocket.sendAllMessage(msg.toJSONString()); -// } -// -// -// // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 -// // (开始巡航时的第一次旋转时间无法计算) -// double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); -// double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); -// Thread.sleep((long) ((obserpoiInfo.getStopTime() + hTime + vTime) * 1000)); -// -// //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; -// -// if (flag) { -// Date date = getTime(-2); -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { -// //推送给前端录像开始时间 -// JSONObject msg = new JSONObject(); -// msg.put("monitorId", obserpoiInfo.getMonitorId()); -// msg.put("type", "alarm"); -// webSocket.sendAllMessage(msg.toJSONString()); -// //报警次数 -// int count = 1; -// String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; -// for (int j = 0; j < commandArr.length; j++) { -// boolean commflag = false; -// //外协设备按照1度上下左右转 -// Date alarmTime = new Date(); -// double dir = 0, pic = 0; -// switch (j) { -// case 1: -// -// case 3: -// -// case 5: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// break; -// case 0: -// dir = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 2: -// dir = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 4: -// pic = -1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// -// case 6: -// pic = 1; -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// case 7: -// ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); -// Thread.sleep(interval / 2); -// if ("1".equals(type)) { -// commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// } else -// commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); -// Thread.sleep(interval); -// break; -// } -// if (commflag) { -// //若当前执行控制治理后查询该设备有报警 -// if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { -// count++; -// } -// } -// } -// if (count < 3) { -// iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.getTime(date), DateUtil.getTime(getTime(2))); -// } -// } -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// /** -// * 计算旋转某个角度所需时间:0.05x + 1.4 -// * -// * @param rotate 旋转角度 -// * @return 时间(秒) -// */ -// private double getRotateTime(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return 0.05 * (rotate % 360) + 1.6; -// } -// } -// -// -// private double getRotateTimeNew(double rotate) { -// if (rotate == 0) { -// return 0; -// } else { -// return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; -// } -// } -// -// -// private Date getTime(int seconds) { -// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); -// Calendar c = new GregorianCalendar(); -// Date date = new Date(); -// c.setTime(date);//设置参数时间 -// c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 -// return c.getTime(); -// } -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IAlarmRecordService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.util.WebSocket; +import org.springframework.stereotype.Component; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * 自动巡航线程 + */ +@Component +public class AutoCruiseTask implements Runnable { + + /** + * 线程退出标记 + */ + public volatile boolean exit = false; + /** + * 巡航点列表 + */ + private List pointList; + /** + * 设备登录ip + */ + private String deviceIp; + /** + * 设备登录id + */ + private Long userId; + + /** + * 设备类型 + */ + private String type; + + /** + * 设备控制service + */ + private IHCNetService ihcNetService; + /** + * + */ + private String monitorName; + + private Integer interval; + private WebSocket webSocket; + + private IAlarmRecordService iAlarmRecordService; + + public AutoCruiseTask() { + } + + public AutoCruiseTask(List pointList, String deviceIp, Long userId, + IHCNetService ihcNetService, WebSocket webSocket, + String type, IAlarmRecordService iAlarmRecordService, + Integer interval, String monitorName) { + this.pointList = pointList; + this.deviceIp = deviceIp; + this.userId = userId; + this.ihcNetService = ihcNetService; + this.webSocket = webSocket; + this.type = type; + this.iAlarmRecordService = iAlarmRecordService; + this.interval = ObjectUtil.isNotEmpty(interval) ? interval : 200; + this.monitorName = monitorName; + } + + /** + * 自动巡航线程: + * 1.查询巡航点 + * 2.发送指令旋转到某个位置 -> 等待(停留)一段时间 -> 发送指令旋转到下个位置 -> ...... + */ + @Override + public void run() { + + + while (!exit) { + // 只要线程未中止,一直循环航线 + for (int i = 0; i < pointList.size(); i++) { + BusObserpoiInfo obserpoiInfo = pointList.get(i); + // 前一个巡航点,用于计算云台旋转所需时间 + BusObserpoiInfo last = pointList.get((i - 1 + pointList.size()) % pointList.size()); + try { + // 如果线程中止,不再转到下一个点 + if (!exit) { + boolean flag = false; + if ("1".equals(type)) { + flag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } else { + flag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection(), obserpoiInfo.getPitch()); + } + // 向前端推送当前预置点编号: + if (ObjectUtil.isNotEmpty(obserpoiInfo.getSerialNum())) { + JSONObject msg = new JSONObject(); + msg.put("deviceIp", this.deviceIp); + msg.put("userId", this.userId); + msg.put("type", "presetIndex"); + msg.put("value", obserpoiInfo.getSerialNum()); + msg.put("name", obserpoiInfo.getSerialName()); + webSocket.sendAllMessage(msg.toJSONString()); + } + + + // 线程等待时间为 从上一巡航点旋转到当前巡航点所需时间 + 当前巡航点停留时间 + // (开始巡航时的第一次旋转时间无法计算) + double hTime = getRotateTimeNew(Math.abs(last.getDirection() - obserpoiInfo.getDirection())); + double vTime = getRotateTimeNew(Math.abs(last.getPitch() - obserpoiInfo.getPitch())); + Thread.sleep((long) (ObjectUtil.isNotEmpty(obserpoiInfo.getStopTime())? + Integer.valueOf(obserpoiInfo.getStopTime()):0+ hTime + vTime) * 1000); + + //根据预置点取浓度是否报警,来执行上下左右转动,若有3个以上点报警则该预置点位置报警; + + if (flag) { + Date date = getTime(-2); + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), date, getTime(2), "")) { + //推送给前端录像开始时间 + JSONObject msg = new JSONObject(); + msg.put("monitorId", obserpoiInfo.getMonitorId()); + msg.put("type", "alarm"); + webSocket.sendAllMessage(msg.toJSONString()); + //报警次数 + int count = 1; + String[] commandArr = {"left", "stop", "right", "stop", "up", "stop", "down", "stop"}; + for (int j = 0; j < commandArr.length; j++) { + boolean commflag = false; + //外协设备按照1度上下左右转 + Date alarmTime = new Date(); + double dir = 0, pic = 0; + switch (j) { + case 1: + + case 3: + + case 5: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + break; + case 0: + dir = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 2: + dir = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 4: + pic = -1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + + case 6: + pic = 1; + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + case 7: + ihcNetService.controlWithSpeedTest(userId.intValue(), commandArr[j], 1, 0); + Thread.sleep(interval / 2); + if ("1".equals(type)) { + commflag = ihcNetService.setPosition(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + } else + commflag = ihcNetService.setPositionNew(userId, obserpoiInfo.getDirection() + dir, obserpoiInfo.getPitch() + pic); + Thread.sleep(interval); + break; + } + if (commflag) { + //若当前执行控制治理后查询该设备有报警 + if (iAlarmRecordService.listByTime(obserpoiInfo.getMonitorId(), alarmTime, new Date(), "")) { + count++; + } + } + } + if (count < 3) { + iAlarmRecordService.clearByMonitorTime(obserpoiInfo.getMonitorId(), DateUtil.formatDateTime(date), DateUtil.formatDateTime(getTime(2))); + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + /** + * 计算旋转某个角度所需时间:0.05x + 1.4 + * + * @param rotate 旋转角度 + * @return 时间(秒) + */ + private double getRotateTime(double rotate) { + if (rotate == 0) { + return 0; + } else { + return 0.05 * (rotate % 360) + 1.6; + } + } + + + private double getRotateTimeNew(double rotate) { + if (rotate == 0) { + return 0; + } else { + return rotate > 180 ? ((360 - rotate) / 360) * 20 : (rotate / 360) * 20; + } + } + + + private Date getTime(int seconds) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Calendar c = new GregorianCalendar(); + Date date = new Date(); + c.setTime(date);//设置参数时间 + c.add(Calendar.SECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + c.add(Calendar.MILLISECOND, seconds);//把日期往后增加SECOND 秒.整数往后推,负数往前移动 + return c.getTime(); + } +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java index 84398ca..c9d9189 100644 --- a/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java +++ b/casic-server/src/main/java/com/casic/missiles/modular/system/task/CollectGasDataTask.java @@ -1,158 +1,158 @@ -//package com.casic.missiles.modular.system.task; -// -//import cn.hutool.core.util.ObjectUtil; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.casic.missiles.modular.system.dto.DeviceCommom; -//import com.casic.missiles.modular.system.dto.DeviceInfo; -//import com.casic.missiles.modular.system.model.BusMonipoiInfo; -//import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; -//import com.casic.missiles.modular.system.service.IHCNetService; -//import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; -//import com.sun.jna.Memory; -//import com.sun.jna.Pointer; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -//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.scheduling.annotation.EnableScheduling; -//import org.springframework.stereotype.Component; -// -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -//import java.util.concurrent.ArrayBlockingQueue; -//import java.util.concurrent.ThreadPoolExecutor; -//import java.util.concurrent.TimeUnit; -// -//@Component -//@EnableScheduling -//public class CollectGasDataTask implements ApplicationRunner { -// private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); -// -// @Autowired -// private IBusMonipoiInfoService monipoiInfoService; -// @Autowired -// private IHCNetService ihcNetService; -// -// @Autowired -// private HCNetServiceImpl hcNetService; -// -// @Value("${casic.presetInterval}") -// private int presetInterval; -// @Value("${casic.collectInterval}") -// private int collectInterval; -// @Value("${casic.isOpen}") -// private int isOpen; -// -// @Override -// public void run(ApplicationArguments args) throws Exception { -// // 查询全部设备 -// QueryWrapper query = new QueryWrapper(); -// query.eq("VALID", "0"); -// List deviceList = monipoiInfoService.list(query); -// // 创建线程池,每个设备一个线程 -// ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, -// new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); -// -// for (BusMonipoiInfo monipoiInfo : deviceList) { -// if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { -// Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); -// executor.execute(worker); -// } -// } -// } -// -// class GasDataRunnable implements Runnable { -// -// private String deviceIp; -// private String deviceUser; -// private String devicePassword; -// private Long userId; -// private Long serialHandle; -// -// public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { -// this.deviceIp = deviceIp; -// this.deviceUser = deviceUser; -// this.devicePassword = devicePassword; -// this.userId = -1L; -// this.serialHandle = -1L; -// } -// -// private boolean registerAndStartSerial() { -// this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); -// this.serialHandle = ihcNetService.serialHandle(userId); -// if (this.userId >= 0 && this.serialHandle >= 0) { -// return true; -// } else { -// return false; -// } -// } -// -// private Map map = new HashMap<>(); -// -// private void sendGasCommand() { -// DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); -// Long serial = deviceInfo.getSerialHandle(); -// if (deviceInfo.getSerialHandle() < 0) { -// return; -// } -// // FF 01 00 90 01 00 92 -// int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; -//// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; -// Pointer pointer = new Memory(command.length); -// for (int i = 0; i < command.length; i++) { -// pointer.setByte(i, (byte) command[i]); -// } -// int size = (int) ((Memory) pointer).getSize(); -// //用于与控制指令错开下发 -// hcNetService.setTimestampCollcect(System.currentTimeMillis()); -// -// boolean res = ihcNetService.serialSend(serial, pointer, size); -//// System.out.println("collect**************"+new Date()); -// if (!res) { -// //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 -// //是否配置重启 -// if (isOpen == 1) { -// if (map.get(this.deviceIp) != null) { -// map.put(this.deviceIp, map.get(this.deviceIp) + 1); -// if (map.get(this.deviceIp) == 300L) { -// if (ihcNetService.interruptStart(this.deviceIp)) { -// map.remove(this.deviceIp); -// logger.error(deviceIp.concat("restart success ********************* ")); -// } -// } -// } else { -// map.put(this.deviceIp, 1); -// } -// } -// logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); -// } -// } -// -// @Override -// public void run() { -// System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); -// // 登录,登录失败就一直尝试登录 -// while (true) { -// boolean register = registerAndStartSerial(); -// if (register) { -// break; -// } -// } -// // 登录成功后,按每秒一次查询甲烷数据 -// while (true) { -// try { -// sendGasCommand(); -// Thread.sleep(collectInterval); -// } catch (InterruptedException e) { -// e.printStackTrace(); -// } -// } -// } -// } -// -// -//} +package com.casic.missiles.modular.system.task; + +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.casic.missiles.modular.system.dto.DeviceCommom; +import com.casic.missiles.modular.system.dto.DeviceInfo; +import com.casic.missiles.modular.system.model.BusMonipoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IHCNetService; +import com.casic.missiles.modular.system.service.impl.HCNetServiceImpl; +import com.sun.jna.Memory; +import com.sun.jna.Pointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.scheduling.annotation.EnableScheduling; +import org.springframework.stereotype.Component; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +@Component +@EnableScheduling +public class CollectGasDataTask implements ApplicationRunner { + private static final Logger logger = LoggerFactory.getLogger(CollectGasDataTask.class); + + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + @Autowired + private IHCNetService ihcNetService; + + @Autowired + private HCNetServiceImpl hcNetService; + + @Value("${casic.presetInterval}") + private int presetInterval; + @Value("${casic.collectInterval}") + private int collectInterval; + @Value("${casic.isOpen}") + private int isOpen; + + @Override + public void run(ApplicationArguments args) throws Exception { + // 查询全部设备 + QueryWrapper query = new QueryWrapper(); + query.eq("VALID", "0"); + List deviceList = monipoiInfoService.list(query); + // 创建线程池,每个设备一个线程 + ThreadPoolExecutor executor = new ThreadPoolExecutor(deviceList.size(), deviceList.size(), 10, TimeUnit.SECONDS, + new ArrayBlockingQueue<>(20), new ThreadPoolExecutor.CallerRunsPolicy()); + + for (BusMonipoiInfo monipoiInfo : deviceList) { + if (ObjectUtil.isNotEmpty(monipoiInfo.getDeviceIp())) { + Runnable worker = this.new GasDataRunnable(monipoiInfo.getDeviceIp(), monipoiInfo.getDeviceUser(), monipoiInfo.getDevicePassword()); + executor.execute(worker); + } + } + } + + class GasDataRunnable implements Runnable { + + private String deviceIp; + private String deviceUser; + private String devicePassword; + private Long userId; + private Long serialHandle; + + public GasDataRunnable(String deviceIp, String deviceUser, String devicePassword) { + this.deviceIp = deviceIp; + this.deviceUser = deviceUser; + this.devicePassword = devicePassword; + this.userId = -1L; + this.serialHandle = -1L; + } + + private boolean registerAndStartSerial() { + this.userId = ihcNetService.register(this.deviceUser, this.devicePassword, this.deviceIp); + this.serialHandle = ihcNetService.serialHandle(userId); + if (this.userId >= 0 && this.serialHandle >= 0) { + return true; + } else { + return false; + } + } + + private Map map = new HashMap<>(); + + private void sendGasCommand() { + DeviceInfo deviceInfo = DeviceCommom.selectByDeviceIp(this.deviceIp); + Long serial = deviceInfo.getSerialHandle(); + if (deviceInfo.getSerialHandle() < 0) { + return; + } + // FF 01 00 90 01 00 92 + int[] command = {0xff, 0x01, 0x00, 0x90, 0x01, 0x00, 0x92}; +// int[] command = {0xff,0x01,0x00,0x53,0x00,0x00,0x54}; + Pointer pointer = new Memory(command.length); + for (int i = 0; i < command.length; i++) { + pointer.setByte(i, (byte) command[i]); + } + int size = (int) ((Memory) pointer).getSize(); + //用于与控制指令错开下发 + hcNetService.setTimestampCollcect(System.currentTimeMillis()); + + boolean res = ihcNetService.serialSend(serial, pointer, size); +// System.out.println("collect**************"+new Date()); + if (!res) { + //判断是否掉线,断电重启规则 若同一云台300次(5分钟)获取不到甲烷浓度值,则重启设备 + //是否配置重启 + if (isOpen == 1) { + if (map.get(this.deviceIp) != null) { + map.put(this.deviceIp, map.get(this.deviceIp) + 1); + if (map.get(this.deviceIp) == 300L) { + if (ihcNetService.interruptStart(this.deviceIp)) { + map.remove(this.deviceIp); + logger.error(deviceIp.concat("restart success ********************* ")); + } + } + } else { + map.put(this.deviceIp, 1); + } + } + logger.error(deviceIp.concat("fetch gas data error, error code: ").concat(String.valueOf(ihcNetService.getLastError()))); + } + } + + @Override + public void run() { + System.out.println("Thread-" + deviceIp + " -> start... " + new Date()); + // 登录,登录失败就一直尝试登录 + while (true) { + boolean register = registerAndStartSerial(); + if (register) { + break; + } + } + // 登录成功后,按每秒一次查询甲烷数据 + while (true) { + try { + sendGasCommand(); + Thread.sleep(collectInterval); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + } + + +} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java deleted file mode 100644 index 20441b5..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/CommDoorUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -@Component -public class CommDoorUtil implements ApplicationRunner { - @Value("${casic.doorips}") - private String doorips; - @Value("${casic.doorsns}") - private String doorsns; - @Value("${casic.monitorids}") - private String monitorids; - @Value("${casic.restartTime}") - private int restartTime; - public final static Map map = new HashMap(); - public static Map flagMap = new HashMap(); - - @Override - public void run(ApplicationArguments args) throws Exception { - if (ObjectUtil.isNotEmpty(doorips)) { - String[] dooripsArr = doorips.split(","); - String[] doorsnsArr = doorsns.split(","); - String[] monitoridsArr = monitorids.split(","); - for (int i = 0; i < dooripsArr.length; i++) { - map.put(monitoridsArr[i], doorsnsArr[i] + "," + dooripsArr[i]); - flagMap.put(monitoridsArr[i], false); - } - map.put("time", restartTime); - } - } - - - //取消防爆箱控制器报警 - public static void cancelControl() { - try { - if (flagMap.get("control")) { - boolean controlFlag = false; - for (Map.Entry entry : flagMap.entrySet()) { - if (entry.getKey().equals("control")) continue; - controlFlag = controlFlag || entry.getValue(); - } - //若所有云台防爆箱都不报警 则控制箱取消报警 -// if (!controlFlag) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { -// flagMap.put("control", false); -// } -// } - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - - //控制云台报警 - public static void controlPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - (!flagMap.get(monitorId))) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) { - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 1)) { - flagMap.put(monitorId, true); -// if (!flagMap.get("control")) { -// String controlStr = map.get("control").toString(); -// if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 1)) { -// flagMap.put("control", true); -// } -// } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //取消云台报警 - public static void cancelPTZ(String monitorId) { - try { - if (ObjectUtil.isNotEmpty(flagMap.get(monitorId)) && - flagMap.get(monitorId)) { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 1, 2)) { - flagMap.put(monitorId, false); - //判断是否取消控制箱报警 -// CommDoorUtil.cancelControl(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重置所有告警 - public static void cancelAllPTZ() { - try { - for (Map.Entry entry : map.entrySet()) { - String controlStr = entry.getValue().toString(); - if (DoorShortUtil.remoteControl(controlStr.split(",")[1], Long.valueOf(controlStr.split(",")[0]), 1, 2)) { - flagMap.put(entry.getKey(), false); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - //重启设备 - public static boolean restart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - return DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - //重启设备 - public static boolean interruptStart(String monitorId) { - try { - String doors = ObjectUtil.isNotEmpty(map.get(monitorId)) ? map.get(monitorId).toString() : ""; - if (ObjectUtil.isNotEmpty(doors)) - if (DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 1)) { - //重新上电需要间隔20秒 - Thread.sleep(Integer.valueOf(map.get("time").toString()) * 1000); - //重新关闭开关上电 - DoorShortUtil.remoteControl(doors.split(",")[1], Long.valueOf(doors.split(",")[0]), 2, 2); - - Thread.sleep(2 * 60 * 1000); - return true; - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java deleted file mode 100644 index dae2f25..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/DoorShortUtil.java +++ /dev/null @@ -1,859 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import cn.hutool.core.util.ObjectUtil; -import org.springframework.scheduling.annotation.Async; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -@Async -public class DoorShortUtil { - - - //单个增加授权 - public static boolean addSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2029年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加起止时间设置授权 - public static boolean addSingleTimeAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String beginDate, - String endDate, String startTime, String endTime) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[5] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[6] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[7] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[9] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[10] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[11] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[30] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[31] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - pkt.data[41] = GetHex(Integer.valueOf(endTime.substring(6, 8))); - } - if (ObjectUtil.isNotEmpty(startTime)) { - pkt.data[42] = GetHex(Integer.valueOf(startTime.substring(0, 2))); - pkt.data[43] = GetHex(Integer.valueOf(startTime.substring(3, 5))); - pkt.data[44] = GetHex(Integer.valueOf(startTime.substring(6, 8))); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 时间段卡授权 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //单个增加时间设置授权 - public static boolean addsetSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, int type) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.11 权限添加或修改[功能号: 0x50] ********************************************************************************** - //增加卡号0D D7 37 00, 通过当前控制器的所有门 - pkt.Reset(); - pkt.functionID = (byte) 0x50; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 29 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - if (type > 1) { - pkt.data[12] = GetHex(type); - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = GetHex(type); //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = GetHex(type); - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = GetHex(type); - } - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器动作. - log("1.11 策略权限添加或修改 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //单个删除授权 - public static boolean deleteSingleAcs(String controllerIP, long controllerSN, - long cardNOOfPrivilege, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.12 权限删除(单个删除)[功能号: 0x52] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - long cardNOOfPrivilegeToDelete = cardNOOfPrivilege; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilegeToDelete), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteSelectedAcs(String controllerIP, long controllerSN, - List cardNOOfPrivileges, String type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - for (Long cardNOOfPrivilege : cardNOOfPrivileges) { - pkt.Reset(); - pkt.functionID = (byte) 0x52; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(cardNOOfPrivilege), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时 刷卡号为= 0x0037D70D = 3659533 (十进制)的卡, 1号门继电器不会动作. - log("1.12 权限删除(单个删除) 成功..."); - success = true; - } - } - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //批量删除授权 - public static boolean deleteBatchAcs(String controllerIP, long controllerSN) { - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.13 权限清空(全部清掉)[功能号: 0x54] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x54; - pkt.iDevSn = controllerSN; - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 0, 4); - - recvBuff = pkt.run(); - success = false; - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //这时清空成功 - log("1.13 权限清空(全部清掉) 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //批量授权 - public static boolean addBatchAcs(String controllerIP, long controllerSN, List cardCodeList) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - //打开udp连接 - pkt.CommOpen(controllerIP); - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 开始..."); - int cardCount = cardCodeList.size(); - for (int i = 0; i < cardCount; i++) { - pkt.Reset(); - pkt.functionID = (byte) 0x56; - pkt.iDevSn = controllerSN; - - System.arraycopy(WgUdpCommShort.longToByte(cardCodeList.get(i)), 0, pkt.data, 0, 4); - //20 10 01 01 起始日期: 2010年01月01日 (必须大于2001年) - pkt.data[4] = 0x20; - pkt.data[5] = 0x10; - pkt.data[6] = 0x01; - pkt.data[7] = 0x01; - //20 59 12 31 截止日期: 2059年12月31日 - pkt.data[8] = 0x20; - pkt.data[9] = 0x59; - pkt.data[10] = 0x12; - pkt.data[11] = 0x31; - //01 允许通过 一号门 [对单门, 双门, 四门控制器有效] - pkt.data[12] = 0x01; - //01 允许通过 二号门 [对双门, 四门控制器有效] - pkt.data[13] = 0x01; //如果禁止2号门, 则只要设为 0x00 - //01 允许通过 三号门 [对四门控制器有效] - pkt.data[14] = 0x01; - //01 允许通过 四号门 [对四门控制器有效] - pkt.data[15] = 0x01; - - - System.arraycopy(WgUdpCommShort.longToByte(cardCount), 0, pkt.data, 32 - 8, 4);//总的权限数 - int i2 = i + 1; - System.arraycopy(WgUdpCommShort.longToByte(i2), 0, pkt.data, 35 - 8, 4);//当前权限的索引位(从1开始) - - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - success = true; - } - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 0xE1) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] =0xE1 表示卡号没有从小到大排序"); - success = false; - break; - } - } else { - success = false; - break; - } - } - if (success == true) { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 成功..."); - } else { - log("1.21 权限按从小到大顺序添加[功能号: 0x56] 失败..."); - } - - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //远程开门 - public static boolean remoteControllAcs(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - - - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.10 远程开门[功能号: 0x40] ********************************************************************************** - int doorNO = 1; - pkt.Reset(); - pkt.functionID = (byte) 0x40; - pkt.iDevSn = controllerSN; - pkt.data[0] = (byte) (doorNO & 0xff); //2013-11-03 20:56:33 - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.10 远程开门 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //提取刷卡记录 - public static Map getCardRecords(String controllerIP, long controllerSN) { - - //1.9 提取记录操作 - //1. 通过 0xB4指令 获取已读取过的记录索引号 recordIndex - //2. 通过 0xB0指令 获取指定索引号的记录 从recordIndex + 1开始提取记录, 直到记录为空为止 - //3. 通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - //经过上面三个步骤, 整个提取记录的操作完成 - List> objectList = new ArrayList<>(); - Map resultMap = new HashMap<>(); - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - //打开udp连接 - pkt.CommOpen(controllerIP); - log(String.format("控制器SN = %d \r\n", controllerSN)); - log("1.9 提取记录操作 开始..."); - pkt.Reset(); - pkt.functionID = (byte) 0xB4; - pkt.iDevSn = controllerSN; - long recordIndexGot4GetSwipe = 0x0; - int recordIndexToGet = 0; - recvBuff = pkt.run(); - if (recvBuff != null) { - recordIndexGot4GetSwipe = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - pkt.Reset(); - pkt.functionID = (byte) 0xB0; - pkt.iDevSn = controllerSN; - long recordIndexToGetStart = recordIndexGot4GetSwipe + 1; - long recordIndexValidGet = 0; - int cnt = 0; - do { - System.arraycopy(WgUdpCommShort.longToByte(recordIndexToGetStart), 0, pkt.data, 0, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - if (recordType == 0) { - break; //没有更多记录 - } - - recordIndexValidGet = recordIndexToGetStart; - //.......对收到的记录作存储处理 - objectList.add(displayRecordInformation(recvBuff)); - - } else { - //提取失败 - System.out.println("*****提取失败"); - break; - } - recordIndexToGetStart++; - } while (cnt++ < 200000); - if (recordIndexValidGet > 0) { - //通过 0xB2指令 设置已读取过的记录索引号 设置的值为最后读取到的刷卡记录索引号 - pkt.Reset(); - pkt.functionID = (byte) 0xB2; - pkt.iDevSn = controllerSN; - System.arraycopy(WgUdpCommShort.longToByte(recordIndexValidGet), 0, pkt.data, 0, 4); - //12 标识(防止误设置) 1 0x55 [固定] - System.arraycopy(WgUdpCommShort.longToByte(WgUdpCommShort.SpecialFlag), 0, pkt.data, 4, 4); - recvBuff = pkt.run(); - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //完全提取成功.... - log("1.9 完全提取成功 成功..."); - success = true; - } - } - - } - } - //关闭udp连接 - pkt.CommClose(); - resultMap.put("success", success); - resultMap.put("list", objectList); - return resultMap; - } - - - /// - /// 显示记录信息 - /// - /// - public static Map displayRecordInformation(byte[] recvBuff) { - Map recordMap = new HashMap<>(); - - long sn = WgUdpCommShort.getLongByByte(recvBuff, 4, 4); - //8-11 最后一条记录的索引号 - //(=0表示没有记录) 4 0x00000000 - long recordIndex = WgUdpCommShort.getLongByByte(recvBuff, 8, 4); - - - //12 记录类型 - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - int recordType = WgUdpCommShort.getIntByByte(recvBuff[12]); - - //13 有效性(0 表示不通过, 1表示通过) 1 - int recordValid = WgUdpCommShort.getIntByByte(recvBuff[13]); - - //14 门号(1,2,3,4) 1 - int recordDoorNO = WgUdpCommShort.getIntByByte(recvBuff[14]); - - //15 进门/出门(1表示进门, 2表示出门) 1 0x01 - int recordInOrOut = WgUdpCommShort.getIntByByte(recvBuff[15]); - - //16-19 卡号(类型是刷卡记录时) - //或编号(其他类型记录) 4 - long recordCardNO = WgUdpCommShort.getLongByByte(recvBuff, 16, 4); - - - //20-26 刷卡时间: - //年月日时分秒 (采用BCD码)见设置时间部分的说明 - String recordTime = String.format("%02X%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[20]), - WgUdpCommShort.getIntByByte(recvBuff[21]), - WgUdpCommShort.getIntByByte(recvBuff[22]), - WgUdpCommShort.getIntByByte(recvBuff[23]), - WgUdpCommShort.getIntByByte(recvBuff[24]), - WgUdpCommShort.getIntByByte(recvBuff[25]), - WgUdpCommShort.getIntByByte(recvBuff[26])); - - //2012.12.11 10:49:59 7 - //27 记录原因代码(可以查 "刷卡记录说明.xls"文件的ReasonNO) - //处理复杂信息才用 1 - int reason = WgUdpCommShort.getIntByByte(recvBuff[27]); - - //0=无记录 - //1=刷卡记录 - //2=门磁,按钮, 设备启动, 远程开门记录 - //3=报警记录 1 - //0xFF=表示指定索引位的记录已被覆盖掉了. 请使用索引0, 取回最早一条记录的索引值 - if (recordType == 0) { - log(String.format("索引位=%u 无记录", recordIndex)); - } else if (recordType == 0xff) { - log(" 指定索引位的记录已被覆盖掉了,请使用索引0, 取回最早一条记录的索引值"); - } else if (recordType == 1) //2015-06-10 08:49:31 显示记录类型为卡号的数据 - { - //卡号 - log(String.format("sn=%d ", sn)); - log(String.format("索引位=%d ", recordIndex)); - log(String.format(" 卡号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 进出 = %s", recordInOrOut == 1 ? "进门" : "出门")); - log(String.format(" 有效 = %s", recordValid == 1 ? "通过" : "禁止")); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - recordMap.put("sn", sn); - recordMap.put("recordIndex", recordIndex); - recordMap.put("recordCardNO", recordCardNO); - recordMap.put("recordDoorNO", recordDoorNO); - recordMap.put("recordInOrOut", recordInOrOut); - recordMap.put("recordValid", recordValid); - recordMap.put("recordTime", recordTime); - recordMap.put("reason", getReasonDetailChinese(reason)); - } else if (recordType == 2) { - //其他处理 - //门磁,按钮, 设备启动, 远程开门记录 - log(String.format("索引位=%d 非刷卡记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } else if (recordType == 3) { - //其他处理 - //报警记录 - log(String.format("索引位=%d 报警记录", recordIndex)); - log(String.format(" 编号 = %d", recordCardNO)); - log(String.format(" 门号 = %d", recordDoorNO)); - log(String.format(" 时间 = %s", recordTime)); - log(String.format(" 描述 = %s", getReasonDetailChinese(reason))); - } - return recordMap; - } - - public static String getReasonDetailChinese(int Reason) //中文 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 3]; //中文信息 - } - - public static String getReasonDetailEnglish(int Reason) //英文描述 - { - if (Reason > 45) { - return ""; - } - if (Reason <= 0) { - return ""; - } - return RecordDetails[(Reason - 1) * 4 + 2]; //英文信息 - } - - public static String RecordDetails[] = - { -//记录原因 (类型中 SwipePass 表示通过; SwipeNOPass表示禁止通过; ValidEvent 有效事件(如按钮 门磁 超级密码开门); Warn 报警事件) -//代码 类型 英文描述 中文描述 - "1", "SwipePass", "Swipe", "刷卡开门", - "2", "SwipePass", "Swipe Close", "刷卡关", - "3", "SwipePass", "Swipe Open", "刷卡开", - "4", "SwipePass", "Swipe Limited Times", "刷卡开门(带限次)", - "5", "SwipeNOPass", "Denied Access: PC Control", "刷卡禁止通过: 电脑控制", - "6", "SwipeNOPass", "Denied Access: No PRIVILEGE", "刷卡禁止通过: 没有权限", - "7", "SwipeNOPass", "Denied Access: Wrong PASSWORD", "刷卡禁止通过: 密码不对", - "8", "SwipeNOPass", "Denied Access: AntiBack", "刷卡禁止通过: 反潜回", - "9", "SwipeNOPass", "Denied Access: More Cards", "刷卡禁止通过: 多卡", - "10", "SwipeNOPass", "Denied Access: First Card Open", "刷卡禁止通过: 首卡", - "11", "SwipeNOPass", "Denied Access: Door Set NC", "刷卡禁止通过: 门为常闭", - "12", "SwipeNOPass", "Denied Access: InterLock", "刷卡禁止通过: 互锁", - "13", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 受刷卡次数限制", - "14", "SwipeNOPass", "Denied Access: Limited Person Indoor", "刷卡禁止通过: 门内人数限制", - "15", "SwipeNOPass", "Denied Access: Invalid Timezone", "刷卡禁止通过: 卡过期或不在有效时段", - "16", "SwipeNOPass", "Denied Access: In Order", "刷卡禁止通过: 按顺序进出限制", - "17", "SwipeNOPass", "Denied Access: SWIPE GAP LIMIT", "刷卡禁止通过: 刷卡间隔约束", - "18", "SwipeNOPass", "Denied Access", "刷卡禁止通过: 原因不明", - "19", "SwipeNOPass", "Denied Access: Limited Times", "刷卡禁止通过: 刷卡次数限制", - "20", "ValidEvent", "Push Button", "按钮开门", - "21", "ValidEvent", "Push Button Open", "按钮开", - "22", "ValidEvent", "Push Button Close", "按钮关", - "23", "ValidEvent", "Door Open", "门打开[门磁信号]", - "24", "ValidEvent", "Door Closed", "门关闭[门磁信号]", - "25", "ValidEvent", "Super Password Open Door", "超级密码开门", - "26", "ValidEvent", "Super Password Open", "超级密码开", - "27", "ValidEvent", "Super Password Close", "超级密码关", - "28", "Warn", "Controller Power On", "控制器上电", - "29", "Warn", "Controller Reset", "控制器复位", - "30", "Warn", "Push Button Invalid: Disable", "按钮不开门: 按钮禁用", - "31", "Warn", "Push Button Invalid: Forced Lock", "按钮不开门: 强制关门", - "32", "Warn", "Push Button Invalid: Not On Line", "按钮不开门: 门不在线", - "33", "Warn", "Push Button Invalid: InterLock", "按钮不开门: 互锁", - "34", "Warn", "Threat", "胁迫报警", - "35", "Warn", "Threat Open", "胁迫报警开", - "36", "Warn", "Threat Close", "胁迫报警关", - "37", "Warn", "Open too long", "门长时间未关报警[合法开门后]", - "38", "Warn", "Forced Open", "强行闯入报警", - "39", "Warn", "Fire", "火警", - "40", "Warn", "Forced Close", "强制关门", - "41", "Warn", "Guard Against Theft", "防盗报警", - "42", "Warn", "7*24Hour Zone", "烟雾煤气温度报警", - "43", "Warn", "Emergency Call", "紧急呼救报警", - "44", "RemoteOpen", "Remote Open Door", "操作员远程开门", - "45", "RemoteOpen", "Remote Open Door By USB Reader", "发卡器确定发出的远程开门" - }; - - public static void log(String info) //日志信息 - { - System.out.println(info); - } - - - //常开、常闭 - public static boolean remoteControl(String controllerIP, long controllerSN, int doorNum, int type) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.17 设置门控制参数(在线/延时) [功能号: 0x80] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x80; - pkt.iDevSn = controllerSN; - //(设置2号门 在线 开门延时 3秒) - //1―常开[不受刷卡控制]; - //2—常闭[不受刷卡控制]; - //3—在线控制(缺省值:3) - pkt.data[0] = 0x01; //几号门 - if (doorNum == 2) { - pkt.data[0] = 0x02; //几号门 - } else if (doorNum == 4) { - pkt.data[0] = 0x04; //几号门 - } - pkt.data[1] = 0x03; //在线 - if (type == 1) { - pkt.data[1] = 0x01; //常开 - } else if (type == 2) { - pkt.data[1] = 0x02; //常闭 - } - pkt.data[2] = 0x03; //开门延时 - recvBuff = pkt.run(); - if (recvBuff != null) { - success = true; - for (int i = 0; i < 3; i++) { - if (pkt.data[i] != recvBuff[8 + i]) { - success = false; - break; - } - } - if (true) { - //成功时, 返回值与设置一致 - log("1.17 设置门控制参数 成功..."); - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - - //策略设置 - public static boolean setStrage(String controllerIP, - long controllerSN, - int dataType, - String week, - String beginDate, - String endDate, - String beginTime, - String endTime) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.20 时段设置 (0x88) [功能号: 0x88] ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x88; - pkt.iDevSn = controllerSN; - - - pkt.data[0] = GetHex(dataType); - //设置开始时间 - pkt.data[1] = 0x20; - pkt.data[2] = 0x20; - pkt.data[3] = 0x01; - pkt.data[4] = 0x01; - if (ObjectUtil.isNotEmpty(beginDate)) { - pkt.data[1] = GetHex(Integer.valueOf(beginDate.substring(0, 2))); - pkt.data[2] = GetHex(Integer.valueOf(beginDate.substring(2, 4))); - pkt.data[3] = GetHex(Integer.valueOf(beginDate.substring(5, 7))); - pkt.data[4] = GetHex(Integer.valueOf(beginDate.substring(8, 10))); - } - //设置结束时间 - pkt.data[5] = 0x20; - pkt.data[6] = 0x59; - pkt.data[7] = 0x02; - pkt.data[8] = 0x21; - if (ObjectUtil.isNotEmpty(endDate)) { - pkt.data[5] = GetHex(Integer.valueOf(endDate.substring(0, 2))); - pkt.data[6] = GetHex(Integer.valueOf(endDate.substring(2, 4))); - pkt.data[7] = GetHex(Integer.valueOf(endDate.substring(5, 7))); - pkt.data[8] = GetHex(Integer.valueOf(endDate.substring(8, 10))); - } - //设置周几可以通行 - pkt.data[9] = 0x01; - pkt.data[10] = 0x01; - pkt.data[11] = 0x01; - pkt.data[12] = 0x01; - pkt.data[13] = 0x01; - pkt.data[14] = 0x01; - pkt.data[15] = 0x01; - - if (ObjectUtil.isNotEmpty(week)) { - for (int i = 9; i <= 15; i++) { - if (!week.contains((i - 8) + "")) { - pkt.data[i] = 0x00; - } - } - } - //设置时间段 - pkt.data[16] = 0x00; - pkt.data[17] = 0x00; - if (ObjectUtil.isNotEmpty(beginTime)) { - pkt.data[16] = GetHex(Integer.valueOf(beginTime.substring(0, 2))); - pkt.data[17] = GetHex(Integer.valueOf(beginTime.substring(3, 5))); - } - pkt.data[18] = 0x23; - pkt.data[19] = 0x59; - if (ObjectUtil.isNotEmpty(endTime)) { - pkt.data[18] = GetHex(Integer.valueOf(endTime.substring(0, 2))); - pkt.data[19] = GetHex(Integer.valueOf(endTime.substring(3, 5))); - } - recvBuff = pkt.run(); - - if (recvBuff != null) { - if (WgUdpCommShort.getIntByByte(recvBuff[8]) == 1) { - //有效开门..... - log("1.20 设置门时间段控制参数 成功..."); - success = true; - } - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - //查询状态 - public static boolean getStatus(String controllerIP, long controllerSN) { - - byte[] recvBuff; - boolean success = false; - WgUdpCommShort pkt = new WgUdpCommShort(); - pkt.iDevSn = controllerSN; - log(String.format("控制器SN = %d \r\n", controllerSN)); - - //打开udp连接 - pkt.CommOpen(controllerIP); - //1.4 查询控制器状态[功能号: 0x20](实时监控用) ********************************************************************************** - pkt.Reset(); - pkt.functionID = (byte) 0x20; - pkt.iDevSn = controllerSN; - recvBuff = pkt.run(); - if (recvBuff != null) { - //读取信息成功... - success = true; - log("1.4 查询控制器状态 成功..."); - - //36 故障号 - //等于0 无故障 - //不等于0, 有故障(先重设时间, 如果还有问题, 则要返厂家维护) 1 - int errCode = WgUdpCommShort.getIntByByte(recvBuff[36]); - - //51 V5.46版本支持 控制器当前年 1 0x13 - //52 V5.46版本支持 月 1 0x06 - //53 V5.46版本支持 日 1 0x22 - - String controllerTime; //控制器当前时间 - controllerTime = String.format("20%02X-%02X-%02X %02X:%02X:%02X", - WgUdpCommShort.getIntByByte(recvBuff[51]), - WgUdpCommShort.getIntByByte(recvBuff[52]), - WgUdpCommShort.getIntByByte(recvBuff[53]), - WgUdpCommShort.getIntByByte(recvBuff[37]), - WgUdpCommShort.getIntByByte(recvBuff[38]), - WgUdpCommShort.getIntByByte(recvBuff[39])); - } else { - log("1.4 查询控制器状态 失败..."); - success = false; - } - //关闭udp连接 - pkt.CommClose(); - return success; - } - - public static byte GetHex(int val) //获取Hex值, 主要用于日期时间格式 - { - return (byte) ((val % 10) + (((val - (val % 10)) / 10) % 10) * 16); - } - - -} - - - - - diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java deleted file mode 100644 index 82ac7fc..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WatchingShortHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.casic.missiles.modular.weigeng; - - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandlerAdapter; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - - -/** - * Class the extends IoHandlerAdapter in order to properly handle - * connections and the data the connections send - * - * @author Apache MINA Project - */ -public class WatchingShortHandler extends IoHandlerAdapter { - - private Queue queue; - public WatchingShortHandler(Queue queue) { - super(); - this.queue = queue; - } - /** - * 异常来关闭session - */ - @Override - public void exceptionCaught(IoSession session, Throwable cause) - throws Exception { - cause.printStackTrace(); - session.close(true); - } - - /** - * 服务器端收到一个消息 - */ - @Override - public void messageReceived(IoSession session, Object message) - throws Exception { - - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if (validBytes.length == WgUdpCommShort.WGPacketSize) - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { -// System.out.println("服务器端关闭session..."); - } - - @Override - public void sessionCreated(IoSession session) throws Exception { -// System.out.println("服务器端成功创建一个session..."); - } - - @Override - public void sessionIdle(IoSession session, IdleStatus status) - throws Exception { - // System.out.println("Session idle..."); - } - - @Override - public void sessionOpened(IoSession session) throws Exception { -// System.out.println("服务器端成功开启一个session..."); - } -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java deleted file mode 100644 index 8d83d5a..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShort.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.future.ConnectFuture; -import org.apache.mina.core.service.IoConnector; -import org.apache.mina.core.session.IoSession; -import org.apache.mina.transport.socket.nio.NioDatagramConnector; - -import java.net.InetSocketAddress; -import java.util.LinkedList; -import java.util.Queue; - -public class WgUdpCommShort { //短报文协议 - - public static final int WGPacketSize = 64; //报文长度 - public static final byte Type = 0x17; //2015-04-30 08:50:29 0x19; //类型 - public static final int ControllerPort = 60000; //控制器端口 - public static final long SpecialFlag = 0x55AAAA55; //特殊标识 防止误操作 - - public static byte[] longToByte(long number) { - byte[] b = new byte[8]; - for (int i = 0; i < 8; i++) { - b[i] = (byte) (number % 256); - number >>= 8; - } - return b; - } - - //将带符号的bt转换为不带符号的int类型数据 - public static int getIntByByte(byte bt) //bt 转换为无符号的int - { - if (bt < 0) { - return (bt + 256); - } else { - return bt; - } - } - - //从字节转换为 long型数据, 最大长度为8字节 低位在前, 高位在后... - //bytlen (1--8), 不在此范围则返回 -1 - public static long getLongByByte(byte[] data, int startIndex, int bytlen) { - long ret = -1; - if ((bytlen >= 1) && (bytlen <= 8)) { - ret = getIntByByte(data[startIndex + bytlen - 1]); - for (int i = 1; i < bytlen; i++) { - ret <<= 8; - ret += getIntByByte(data[startIndex + bytlen - 1 - i]); - } - } - return ret; - } - - - public byte functionID; //功能号 - public long iDevSn; //设备序列号 4字节 - public byte[] data = new byte[56]; //56字节的数据 [含流水号] - - private static long _Global_xid = 0; - protected long _xid = 0; //2011-5-12 15:28:37 - - void GetNewXid() //2011-1-10 14:22:16 获取新的Xid - { - _Global_xid++; - _xid = _Global_xid; //新的值 - } - - static long getXidOfCommand(byte[] cmd) //获取指令中的xid - { - long ret = -1; - if (cmd.length >= WGPacketSize) { - ret = getLongByByte(cmd, 40, 4); - } - return ret; - } - - public WgUdpCommShort() { - Reset(); - } - - public void Reset() //数据复位 - { - for (int i = 0; i < data.length; i++) { - data[i] = 0; - } - } - - public byte[] toByte() //生成64字节指令包 - { - byte[] buff = new byte[WGPacketSize]; - for (int i = 0; i < data.length; i++) { - buff[i] = 0; - } - buff[0] = Type; - buff[1] = functionID; - System.arraycopy(longToByte(iDevSn), 0, buff, 4, 4); - System.arraycopy(data, 0, buff, 8, data.length); - - GetNewXid(); - System.arraycopy(longToByte(_xid), 0, buff, 40, 4); - return buff; - } - - - Queue queue; - IoConnector connector; // = new NioDatagramConnector(); - ConnectFuture connFuture; - - public void CommOpen(String ip, int port) { - queue = new LinkedList(); - connector = new NioDatagramConnector(); - connector.setHandler(new WgUdpCommShortHandler(queue)); - connFuture = connector.connect(new InetSocketAddress(ip, port)); - } - - //打开通信连接 - public void CommOpen(String ip) { - CommOpen(ip, ControllerPort); - } - - //关闭通信连接 - public void CommClose() { - try { - IoSession session = connFuture.getSession(); - if (session != null) { - session.close(true); - } - connector.dispose(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - //运行 获取通信数据 - //失败时, 返回 null, 否则为64字节数据 - public byte[] run() { - try { - return getInfo(iDevSn, toByte()); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - //通过指定sn和command 获取数据 - public byte[] getInfo(long sn, byte[] command) { - byte[] bytCommand = command; - IoBuffer b; - IoSession session = connFuture.getSession(); - Boolean bSent = false; - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - - int bSuccess = 0; - int tries = 3; - long xid = getXidOfCommand(bytCommand); - byte[] bytget = null; - while ((tries--) > 0) { - long startTicks = java.util.Calendar.getInstance().getTimeInMillis(); // DateTime.Now.Ticks; - long CommTimeoutMsMin = 300; - long endTicks = startTicks + CommTimeoutMsMin; - if (startTicks > endTicks) { - //System.out.println("超时"); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - continue; - } - long startIndex = 0; - while (endTicks > java.util.Calendar.getInstance().getTimeInMillis()) { - if (!bSent) //没有发送过.... - { - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - bSent = true; - } - } - } - if (!queue.isEmpty()) { - synchronized (queue) { - bytget = queue.poll(); - } - if ((bytget[0] == bytCommand[0]) //类型一致 - && (bytget[1] == bytCommand[1]) //功能号一致 - && (xid == getXidOfCommand(bytget))) //序列号对应 - { - bSuccess = 1; - break; // return ret; - } else { - //System.out.printf("无效包 xid=%d\r\n", WgUdpComm.getXidOfCommand(bytget)); - } - } else { - if ((startTicks + 1) < java.util.Calendar.getInstance().getTimeInMillis()) { - } else if (startIndex > 10) { - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } else { - startIndex++; - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - } - if (bSuccess > 0) { - break; - } else { - // System.out.println("重试...."); - session = connFuture.getSession(); - if (session != null) { - if (session.isConnected()) { - b = IoBuffer.allocate(bytCommand.length); - b.put(bytCommand); - b.flip(); - session.write(b); - } - } - } - } - - if (bSuccess > 0) { - //System.out.println("通信 成功"); - return bytget; - } else { - //System.out.println("通信 失败...."); - } - return null; - } - -} diff --git a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java b/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java deleted file mode 100644 index 1878fff..0000000 --- a/casic-server/src/main/java/com/casic/missiles/modular/weigeng/WgUdpCommShortHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.casic.missiles.modular.weigeng; - -import org.apache.mina.core.buffer.IoBuffer; -import org.apache.mina.core.service.IoHandler; -import org.apache.mina.core.session.IdleStatus; -import org.apache.mina.core.session.IoSession; - -import java.util.Queue; - -public class WgUdpCommShortHandler implements IoHandler { - - public Queue queue; - - public WgUdpCommShortHandler() { - } - - public WgUdpCommShortHandler(Queue queue) { - super(); - this.queue = queue; - } - - public void exceptionCaught(IoSession session, Throwable e) - throws Exception { - e.printStackTrace(); - session.close(true); - } - - public void messageReceived(IoSession session, Object message) - throws Exception { - IoBuffer io = (IoBuffer) message; - if (io.hasRemaining()) - { - byte[] validBytes = new byte[io.remaining()]; - io.get(validBytes,0,io.remaining()); - if ((validBytes.length == WgUdpCommShort.WGPacketSize) - && (validBytes[0] == WgUdpCommShort.Type)) //型号固定 - { - synchronized (queue) - { - queue.offer(validBytes); - } - } - else - { - //System.out.print("收到无效数据包: ????\r\n"); - } - //System.out.println(""); - } - } - - public void messageSent(IoSession session, Object message) throws Exception { - - } - - public void sessionClosed(IoSession session) throws Exception { - - } - - public void sessionCreated(IoSession session) throws Exception { - - } - - public void sessionIdle(IoSession session, IdleStatus idle) - throws Exception { - - } - - public void sessionOpened(IoSession session) throws Exception { - - } - -} diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java index 8e5f709..7fbf4f8 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusMonipoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.core.datascope.DataScope; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import org.apache.ibatis.annotations.Param; @@ -22,4 +23,5 @@ List monitorListPage(@Param("scope") DataScope dataScope, @Param("stationId")Long stationId,@Param("keyword")String keyword); + MonitorBaseInfo selectInfoByDeviceIp(@Param("deviceIp") String deviceIp); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java index 6a02d31..11f9bfc 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/BusObserpoiInfoMapper.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import org.apache.ibatis.annotations.Param; /** *

@@ -12,5 +13,13 @@ * @since 2023-04-18 */ public interface BusObserpoiInfoMapper extends BaseMapper { + Integer selectMaxNum(@Param("monitorId") Long monitorId, @Param("lineNum") Integer lineNum); + + boolean updateCruise(@Param("monitorId")Long monitorId, + @Param("cruiseName")String cruiseName, + @Param("cruiseRoute")Integer cruiseRoute); + + Integer selectByMonitorByCruiseName(@Param("monitorId") Long monitorId, + @Param("cruiseName") String cruiseName); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml index 93e341e..8599633 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusMonipoiInfoMapper.xml @@ -69,5 +69,17 @@ - + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml index 0c6996c..8b833e6 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/dao/mapping/BusObserpoiInfoMapper.xml @@ -23,5 +23,24 @@ ID AS id, SERIAL_NAME AS serialName, SERIAL_NUM AS serialNum, DIRECTION AS direction, PITCH AS pitch, MONITOR_ID AS monitorId, STOP_TIME AS stopTime, ALARM_VALUE AS alarmValue, SPEED AS speed, LINE_NUM AS lineNum, LINE_NAME AS lineName, UPDATE_TIME AS updateTime, TS AS ts - + + + update bus_obserpoi_info + set LINE_NAME = #{cruiseName} + where MONITOR_ID = #{monitorId} + and LINE_NUM = #{cruiseRoute} + + diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java index f4a193a..056cc36 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/model/BusObserpoiInfo.java @@ -57,17 +57,17 @@ * 停留时间 */ @TableField("STOP_TIME") - private String stopTime; + private Integer stopTime; /** * 报警阈值 */ @TableField("ALARM_VALUE") - private String alarmValue; + private Integer alarmValue; /** * 速度 */ @TableField("SPEED") - private String speed; + private Integer speed; /** * 巡航线序号 */ @@ -88,7 +88,14 @@ */ @TableField("TS") private Date ts; + public BusObserpoiInfo() { + } + public BusObserpoiInfo(Double direction, Double pitch, Integer stopTime) { + this.direction = direction; + this.pitch = pitch; + this.stopTime = stopTime; + } @Override public String toString() { diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java index eeac8b8..e3afbe1 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusMonipoiInfoService.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.baomidou.mybatisplus.extension.service.IService; @@ -30,4 +31,10 @@ ResponseData monitorDetail(Long id); + MonitorBaseInfo selectInfoByDeviceIp(String deviceIp); + + BusMonipoiInfo selectByDeviceIp(String deviceIp); + + void updateBusMonipoiInfo(String deviceIp,int lineNum); + } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java index 8bf83e0..9389234 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/IBusObserpoiInfoService.java @@ -3,6 +3,8 @@ import com.casic.missiles.modular.system.model.BusObserpoiInfo; import com.baomidou.mybatisplus.extension.service.IService; +import java.util.List; + /** *

* 巡航预置点信息表 服务类 @@ -12,5 +14,34 @@ * @since 2023-04-18 */ public interface IBusObserpoiInfoService extends IService { + List selectByMonitor(String deviceIp, Integer lineNum); + + List selectByMonitor(Long monitorId,Integer lineNum); + + Integer selectMaxNum(Long monitorId,Integer lineNum); + + boolean addPresetByIp(String deviceIp, int presetIndex,int cruiseRoute, + double direction, double pitch, int stopTime, + int alarmValue,int speed,String presetName, + String cruiseName); + + List selectBeforesBySerialNum(String deviceIp,Integer lineNum,Integer serialNum); + + boolean deletePresetBySerials(String deviceIp, int presetIndex,int cruiseRoute ); + + boolean deletePresetByIp(String deviceIp, int presetIndex,int cruiseRoute ); + + BusObserpoiInfo selectByMonitorAndNum(Long monitorId, Integer serialNum,Integer lineNum); + + boolean updateGlobalValues(String deviceIp, Integer stopTime, + Integer alarmValue, Integer speed); + + boolean updateCruise(Long monitorId, String cruiseName,int cruiseRoute ); + + List selectByMonitor(String deviceIp); + + Integer selectByMonitorByCruiseName(Long monitorId,String cruiseName); + + boolean deleteCruise(String deviceIp, String cruiseName,int cruiseRoute ); } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java index 6c168f3..f05c778 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusMonipoiInfoServiceImpl.java @@ -1,5 +1,7 @@ package com.casic.missiles.modular.system.service.impl; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.casic.missiles.core.application.context.AbstractPermissionContext; @@ -7,6 +9,7 @@ import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.response.ResponseData; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; import com.casic.missiles.modular.system.dto.MonitorPointList; import com.casic.missiles.modular.system.model.BusMonipoiInfo; import com.casic.missiles.modular.system.dao.BusMonipoiInfoMapper; @@ -15,6 +18,7 @@ import com.casic.missiles.util.DictCodeUtils; import lombok.AllArgsConstructor; import org.apache.commons.lang3.StringUtils; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; @@ -42,11 +46,11 @@ } @Override - public Page monitorListPage(Page page, Long stationId, String keyword)throws Exception { + public Page monitorListPage(Page page, Long stationId, String keyword) throws Exception { DataScope dataScope = permissionContext.getAuthService().getLoginUserDataScope(); dataScope.setScopeName("DEPT_ID"); List monitorPointLists = this.baseMapper.monitorListPage(dataScope, stationId, keyword); - for(BusMonipoiInfo busMonipoiInfo:monitorPointLists){ + for (BusMonipoiInfo busMonipoiInfo : monitorPointLists) { DictCodeUtils.convertDictCodeToName(busMonipoiInfo); } page.setRecords(monitorPointLists); @@ -86,4 +90,33 @@ return ResponseData.success(busMonipoiInfo); } + @Override + @Cacheable(value = {"PAN-TILT"}, key = "'monitor_info_ip-'+#deviceIp") + public MonitorBaseInfo selectInfoByDeviceIp(String deviceIp) { + return this.baseMapper.selectInfoByDeviceIp(deviceIp); + } + + @Override + @Cacheable(value = {"PAN-TILT"}, key = "'bus_monitor_info_ip-'+#deviceIp") + public BusMonipoiInfo selectByDeviceIp(String deviceIp) { + QueryWrapper query = new QueryWrapper(); + query.eq("DEVICE_IP", deviceIp); + query.eq("VALID", "0"); + List list = this.list(query); + if (ObjectUtil.isNotEmpty(list)) { + return list.get(0); + } + return null; + } + + + @Override + public void updateBusMonipoiInfo(String deviceIp, int lineNum) { + BusMonipoiInfo busMonipoiInfo=selectByDeviceIp(deviceIp); + if(null!=busMonipoiInfo){ + busMonipoiInfo.setLineNum(lineNum); + this.baseMapper.updateById(busMonipoiInfo); + } + } + } diff --git a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusObserpoiInfoServiceImpl.java b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusObserpoiInfoServiceImpl.java index 877bfd9..13c646c 100644 --- a/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusObserpoiInfoServiceImpl.java +++ b/casic-station/src/main/java/com/casic/missiles/modular/system/service/impl/BusObserpoiInfoServiceImpl.java @@ -1,11 +1,19 @@ package com.casic.missiles.modular.system.service.impl; -import com.casic.missiles.modular.system.model.BusObserpoiInfo; -import com.casic.missiles.modular.system.dao.BusObserpoiInfoMapper; -import com.casic.missiles.modular.system.service.IBusObserpoiInfoService; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.casic.missiles.modular.system.dao.BusObserpoiInfoMapper; +import com.casic.missiles.modular.system.dto.MonitorBaseInfo; +import com.casic.missiles.modular.system.model.BusObserpoiInfo; +import com.casic.missiles.modular.system.service.IBusMonipoiInfoService; +import com.casic.missiles.modular.system.service.IBusObserpoiInfoService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Date; +import java.util.List; + /** *

* 巡航预置点信息表 服务实现类 @@ -16,6 +24,195 @@ */ @Service public class BusObserpoiInfoServiceImpl extends ServiceImpl implements IBusObserpoiInfoService { + @Autowired + private IBusMonipoiInfoService monipoiInfoService; + + @Override + public BusObserpoiInfo selectByMonitorAndNum(Long monitorId, Integer serialNum, Integer lineNum) { + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", monitorId); + query.eq("SERIAL_NUM", serialNum); + query.eq("LINE_NUM", lineNum); + return this.getOne(query); + } + + @Override + public List selectByMonitor(Long monitorId, Integer lineNum) { + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", monitorId); + if (ObjectUtil.isNotEmpty(lineNum)) { + query.eq("LINE_NUM", lineNum); + } + query.setParamAlias("ID as id, SERIAL_NUM as serialNum,LINE_NUM as lineNum, " + + "DIRECTION as direction, PITCH as pitch,STOP_TIME as stopTime, SPEED as speed, " + + "LINE_NAME as lineName,SERIAL_NAME as serialName,ALARM_VALUE as alarmValue"); + query.orderByAsc("SERIAL_NUM"); + return this.list(query); + } + + @Override + public List selectByMonitor(String deviceIp, Integer linNum) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", baseInfo.getMonitorId()); + query.eq("LINE_NUM", linNum); + query.isNotNull("DIRECTION"); + query.isNotNull("PITCH"); + query.isNotNull("STOP_TIME"); + query.orderByAsc("SERIAL_NUM"); + return this.list(query); + } + return null; + } + + @Override + public List selectBeforesBySerialNum(String deviceIp, Integer linNum, Integer serialNum) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", baseInfo.getMonitorId()); + query.eq("LINE_NUM", linNum); + query.gt("SERIAL_NUM", serialNum); + query.orderByAsc("SERIAL_NUM"); + return this.list(query); + } + return null; + } + @Override + public Integer selectMaxNum(Long monitorId, Integer lineNum) { + return this.baseMapper.selectMaxNum(monitorId, lineNum); + } + + + @Override + public boolean addPresetByIp(String deviceIp, int presetIndex, int lineNum, + double direction, double pitch, int stopTime, + int alarmValue, int speed, String presetName, + String cruiseName) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + BusObserpoiInfo check = this.selectByMonitorAndNum(baseInfo.getMonitorId(), presetIndex, lineNum); + if (ObjectUtil.isNotEmpty(check)) { + BusObserpoiInfo old = check; + old.setDirection(direction); + old.setPitch(pitch); + old.setStopTime(stopTime); + old.setAlarmValue(alarmValue); + old.setSpeed(speed); + old.setSerialName(presetName); + old.setLineName(cruiseName); + old.setSpeed(speed); + old.setTs(new Date()); + return this.updateById(old); + } else { + BusObserpoiInfo obserpoiInfo = new BusObserpoiInfo(); + obserpoiInfo.setMonitorId(baseInfo.getMonitorId()); + obserpoiInfo.setSerialNum(presetIndex); + obserpoiInfo.setLineNum(lineNum); + obserpoiInfo.setDirection(direction); + obserpoiInfo.setPitch(pitch); + obserpoiInfo.setStopTime(stopTime); + obserpoiInfo.setAlarmValue(alarmValue); + obserpoiInfo.setSpeed(speed); + obserpoiInfo.setSerialName(presetName); + obserpoiInfo.setLineName(cruiseName); + return this.save(obserpoiInfo); + } + } + return false; + } + + + @Override + public boolean deletePresetByIp(String deviceIp, int presetIndex, int lineNum) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper ew = new QueryWrapper<>(); + ew.eq("MONITOR_ID", baseInfo.getMonitorId()); + ew.eq("SERIAL_NUM", presetIndex); + ew.eq("LINE_NUM", lineNum); + return this.remove(ew); + } + return false; + } + + + @Override + public boolean deletePresetBySerials(String deviceIp, int presetIndex, int lineNum) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper ew = new QueryWrapper<>(); + ew.eq("MONITOR_ID", baseInfo.getMonitorId()); + ew.gt("SERIAL_NUM", presetIndex); + ew.eq("LINE_NUM", lineNum); + return this.remove(ew); + } + return false; + } + + + //根据全局变量设置属性值 + @Override + public boolean updateGlobalValues(String deviceIp, Integer stopTime, + Integer alarmValue, Integer speed) { + + List busObserpoiInfoList = selectByMonitor(deviceIp); + if (ObjectUtil.isNotEmpty(busObserpoiInfoList)) { + busObserpoiInfoList.forEach(busObserpoiInfo -> { + if (ObjectUtil.isNotEmpty(stopTime)) { + busObserpoiInfo.setStopTime(stopTime); + } + if (ObjectUtil.isNotEmpty(alarmValue)) { + busObserpoiInfo.setAlarmValue(alarmValue); + } + if (ObjectUtil.isNotEmpty(speed)) { + busObserpoiInfo.setSpeed(speed); + } + }); + this.updateBatchById(busObserpoiInfoList); + } + return true; + } + + @Override + public boolean updateCruise(Long monitorId, String cruiseName, int cruiseRoute) { + + return this.baseMapper.updateCruise(monitorId, cruiseName, cruiseRoute); + } + + @Override + public List selectByMonitor(String deviceIp) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper query = new QueryWrapper<>(); + query.eq("MONITOR_ID", baseInfo.getMonitorId()); + query.isNotNull("DIRECTION"); + query.isNotNull("PITCH"); + query.isNotNull("STOP_TIME"); + query.orderByAsc("SERIAL_NUM"); + return this.list(query); + } + return null; + } + + @Override + public Integer selectByMonitorByCruiseName(Long monitorId, String cruiseName) { + return this.baseMapper.selectByMonitorByCruiseName(monitorId, cruiseName); + } + + + @Override + public boolean deleteCruise(String deviceIp, String cruiseName, int cruiseRoute) { + MonitorBaseInfo baseInfo = monipoiInfoService.selectInfoByDeviceIp(deviceIp); + if (ObjectUtil.isNotEmpty(baseInfo)) { + QueryWrapper ew = new QueryWrapper<>(); + ew.eq("MONITOR_ID", baseInfo.getMonitorId()); + ew.eq("LINE_NUM", cruiseRoute); + return this.remove(ew); + } + return false; + } }