commit c4fe9ca9363ebb0514b2ff9773d2bef888dc4d51 Author: gdxs Date: Wed Jun 5 23:18:31 2024 +0800 集中器服务拆分 diff --git a/carCheck/conn.properties b/carCheck/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/carCheck/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/carCheck/pom.xml b/carCheck/pom.xml new file mode 100644 index 0000000..d01e908 --- /dev/null +++ b/carCheck/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + carCheck + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/carCheck/src/main/java/com/back/instance/WebsocketConnectInstance.java b/carCheck/src/main/java/com/back/instance/WebsocketConnectInstance.java new file mode 100644 index 0000000..9c39e54 --- /dev/null +++ b/carCheck/src/main/java/com/back/instance/WebsocketConnectInstance.java @@ -0,0 +1,24 @@ +package com.back.instance; + +public class WebsocketConnectInstance { + + public static WebsocketConnectInstance websocketConnectInstance = null; + + public static WebsocketConnectInstance getInstance() { + if (websocketConnectInstance == null) { + websocketConnectInstance = new WebsocketConnectInstance(); + } + return websocketConnectInstance; + } + + private boolean restart; + + public boolean isRestart() { + return restart; + } + + public void setRestart(boolean restart) { + this.restart = restart; + } + +} diff --git a/carCheck/src/main/java/com/back/main/MainProcess.java b/carCheck/src/main/java/com/back/main/MainProcess.java new file mode 100644 index 0000000..0667cb6 --- /dev/null +++ b/carCheck/src/main/java/com/back/main/MainProcess.java @@ -0,0 +1,65 @@ +package com.back.main; + +import com.back.common.RunParams; +import com.back.instance.WebsocketConnectInstance; +import com.back.protocol.SystemParameter; +import com.back.webSocket.CarCheckSocket; +import com.back.webSocket.SocketServer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.UnknownHostException; +import java.util.TimeZone; +import java.util.Timer; +import java.util.TimerTask; + +public class MainProcess { + + public static final Logger LOGGER = LoggerFactory.getLogger(MainProcess.class); + + public static void main(String[] args) { + + System.out.println("ver 1.2.11 2019-03-24 17");// 英文 + System.out.println(TimeZone.getDefault().getDisplayName()); + // 获取运行参数 + RunParams runParams = SystemParameter.GetPostParams(); + if (runParams == null) { + System.out.println("Database connection failed!"); + } + int websocketPort = runParams.websocketPort; + String carCheckSocketIp = runParams.carCheckSocketIp; + int carCheckSocketPort = runParams.carCheckSocketPort; + + // 车检器 + try { + try { + SocketServer socketServer = new SocketServer(websocketPort); + socketServer.start(); + + // 定时判断 websocket 是否假死(3分钟) + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + try { + WebsocketConnectInstance websocketConnectInstance = WebsocketConnectInstance.getInstance(); +// if (websocketConnectInstance.isRestart()) { +// socketServer.stop(); +// socketServer.start(); +// } + } catch (Exception e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + System.err.println("socketServer 重启发生异常"); + } + } + }, 0, 1 * 1000); + + } catch (UnknownHostException e) { + LOGGER.error("websocket 连接失败,error message:{}", e.getMessage()); + } + new CarCheckSocket(carCheckSocketIp, carCheckSocketPort).connectCarCheckSocket(); + } catch (Exception e) { + LOGGER.error("车检器 socket 连接失败,error message:{}", e.getMessage()); + } + } +} diff --git a/carCheck/src/main/java/com/back/webSocket/CarCheckSocket.java b/carCheck/src/main/java/com/back/webSocket/CarCheckSocket.java new file mode 100644 index 0000000..34bc49a --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/CarCheckSocket.java @@ -0,0 +1,1174 @@ +package com.back.webSocket; + +import java.io.DataInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +import com.back.webSocket.bean.*; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.alibaba.fastjson.JSON; +import com.back.action.Log; +import com.back.common.Common; +import com.back.jdbc.SQLHelper; +import com.back.protocol.SystemParameter; +import com.back.threadpool.ThreadPool; + + +public class CarCheckSocket { + + public static final Logger LOGGER = LoggerFactory.getLogger(CarCheckSocket.class); + + private String socketIp; + + private int port; + + LocalDateTime insertTime = null; + + private static ThreadPool threadPool; + int threadsize = SystemParameter.runParams.threadsize; + String language = SystemParameter.runParams.language; + int carCheckSocketTimeOut = SystemParameter.runParams.carCheckSocketTimeOut / 1000; + int carCheckSocketSaveInteval = SystemParameter.runParams.carCheckSocketSaveInteval / 60; + + private ConcurrentHashMap threadMap = new ConcurrentHashMap<>(); + + public CarCheckSocket(String socketIp, int port) { + super(); + this.socketIp = socketIp; + this.port = port; + + threadPool = ThreadPool.getInstance(threadsize, language);// 创建线程池 + try { + Thread.sleep(500);// 休眠500毫秒,以便让线程池中的工作线程全部运行 + } catch (InterruptedException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public void connectCarCheckSocket() throws IOException { + try { + // 1. 前置机启动时,查询车检器集合 + String carCheckSensorSql = "select s.id, s.name, s.comid, s.terminal, s.floorNo, s.ip, s.port, s.lane, s.lanelength, " + + " s.laneflag, s.laneweight1, s.laneweight2, s.laneweight3, s.laneweight4, " + + " s.laneweight5, s.laneweight6, s.laneweight7, s.laneweight8, s.connectflag, s.productid, t.line, sp.ip spip, " + + " sp.port spport, sp.lane splane, sp.lanelength splanelength, sp.laneflag splaneflag, " + + " sp.laneweight1 splaneweight1, sp.laneweight2 splaneweight2, sp.laneweight3 splaneweight3, " + + " sp.laneweight4 splaneweight4, sp.laneweight5 splaneweight5, sp.laneweight6 splaneweight6, " + + " sp.laneweight7 splaneweight7, sp.laneweight8 splaneweight8 from sensors s " + + " left join sensorproduct sp on s.productid = sp.id " + + " left join terminals t on s.terminal = t.comid " + + " where ((s.productid is null and s.type = '0004' and s.ip is not null and s.port is not null) or " + + " (s.productid is not null and sp.devicetype = '0004' and sp.ip is not null and sp.port is not null)) "; + List sensorInfoList = selectSensor(carCheckSensorSql); + + System.out.println("sensorInfoList: " + JSON.toJSONString(sensorInfoList)); + for (CarSensor carSensor : sensorInfoList) { + // 启动连接 socket 任务 +// threadPool.execute(carSensor.getTerminal(), 1, connectSocketTask(carSensor)); + addThread(carSensor); + + Thread.sleep(1 * 1000); + } + + System.out.println("第三方车检器服务器连接完成,threadMap: " + JSON.toJSONString(threadMap)); + + // 第三方车检器检测连接定时任务 + Timer carCheckTimer = new Timer(); + carCheckTimer.schedule(new TimerTask() { + + @Override + public void run() { + System.out.println(String.format("当前时间:%s,正在连接的第三方车检器服务器,IP、端口集合: %s", + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), + JSON.toJSONString(threadMap.keys()))); + + // 查询需要重新连接第三方传感器 + String sensorSql = "select s.id, s.name, s.comid, s.terminal, s.floorNo, s.ip, s.port, s.lane, s.lanelength, s.laneflag, " + + " s.laneweight1, s.laneweight2, s.laneweight3, s.laneweight4, s.laneweight5, s.laneweight6, s.laneweight7, s.laneweight8, " + + " s.connectflag, s.productid, t.line, sp.ip spip, sp.port spport, sp.lane splane, sp.lanelength splanelength, sp.laneflag splaneflag, " + + " sp.laneweight1 splaneweight1, sp.laneweight2 splaneweight2, sp.laneweight3 splaneweight3, sp.laneweight4 splaneweight4, " + + " sp.laneweight5 splaneweight5, sp.laneweight6 splaneweight6, sp.laneweight7 splaneweight7, sp.laneweight8 splaneweight8 " + + " from sensors s left join sensorproduct sp on s.productid = sp.id left join terminals t on s.terminal = t.comid " + + " where ((s.productid is null and s.type = '0004' and s.ip is not null and s.port is not null) or " + + " (s.productid is not null and sp.devicetype = '0004' and sp.ip is not null and sp.port is not null)) "; + try { + List selectSensor = selectSensor(sensorSql); + System.out.println("sensorInfoList: " + JSON.toJSONString(selectSensor)); + // 需要移除的 socket 连接 + List removeSocketConnectList = new ArrayList<>(); + for (Map.Entry entry : threadMap.entrySet()) { + String[] keyArray = entry.getKey().split("_"); + String comid = keyArray[0]; + String ip = keyArray[1]; + String port = keyArray[2]; + CarSensor carSensor = selectSensor.stream() + .filter(sensor -> sensor.getComid().equals(comid) + && sensor.getIp().equals(ip) + && sensor.getPort().equals(port)) + .findFirst().orElse(null); + if (carSensor == null) { + System.out.println("移除key" + entry.getKey()); + removeSocketConnectList.add(entry.getKey()); + } + } + + for (String key : removeSocketConnectList) { + removeThread(key); + } + + // 需要新增的 socket 连接 + List addSocketConnectList = selectSensor.stream().filter(sensor -> sensor.getConnectflag() == 1).collect(Collectors.toList()); + for (CarSensor carSensor : addSocketConnectList) { + addThread(carSensor); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + }, 30 * 1000, 3 * 60 * 1000); + } catch (Exception e) { + System.out.println("error msg: " + e.getMessage()); + e.printStackTrace(); + } + } + + private List selectSensor(String carCheckSensorSql) throws SQLException { + List sensorInfoList = new ArrayList<>(); + ResultSet carCheckSensorSet = SQLHelper.ExecProcwCommands(carCheckSensorSql); + if (carCheckSensorSet != null) { + while (carCheckSensorSet.next()) { + CarSensor carSensor = new CarSensor(); + carSensor.setName(carCheckSensorSet.getString("name")); + carSensor.setComid(carCheckSensorSet.getString("comid")); + carSensor.setTerminal(carCheckSensorSet.getString("terminal")); + + String ip; + String port; + int lane; + int lanelength; + String laneflag; + int laneweight1; + int laneweight2; + int laneweight3; + int laneweight4; + int laneweight5; + int laneweight6; + int laneweight7; + int laneweight8; + + int id = carCheckSensorSet.getInt("id"); + int connectflag = carCheckSensorSet.getInt("connectflag"); + String productid = carCheckSensorSet.getString("productid"); + if (StringUtils.isNotEmpty(productid)) { + ip = carCheckSensorSet.getString("spip"); + port = carCheckSensorSet.getString("spport"); + lane = carCheckSensorSet.getInt("splane"); + lanelength = carCheckSensorSet.getInt("splanelength"); + laneflag = carCheckSensorSet.getString("splaneflag"); + laneweight1 = carCheckSensorSet.getInt("splaneweight1"); + laneweight2 = carCheckSensorSet.getInt("splaneweight2"); + laneweight3 = carCheckSensorSet.getInt("splaneweight3"); + laneweight4 = carCheckSensorSet.getInt("splaneweight4"); + laneweight5 = carCheckSensorSet.getInt("splaneweight5"); + laneweight6 = carCheckSensorSet.getInt("splaneweight6"); + laneweight7 = carCheckSensorSet.getInt("splaneweight7"); + laneweight8 = carCheckSensorSet.getInt("splaneweight8"); + + } else { + ip = carCheckSensorSet.getString("ip"); + port = carCheckSensorSet.getString("port"); + lane = carCheckSensorSet.getInt("lane"); + lanelength = carCheckSensorSet.getInt("lanelength"); + laneflag = carCheckSensorSet.getString("laneflag"); + laneweight1 = carCheckSensorSet.getInt("laneweight1"); + laneweight2 = carCheckSensorSet.getInt("laneweight2"); + laneweight3 = carCheckSensorSet.getInt("laneweight3"); + laneweight4 = carCheckSensorSet.getInt("laneweight4"); + laneweight5 = carCheckSensorSet.getInt("laneweight5"); + laneweight6 = carCheckSensorSet.getInt("laneweight6"); + laneweight7 = carCheckSensorSet.getInt("laneweight7"); + laneweight8 = carCheckSensorSet.getInt("laneweight8"); + + } + carSensor.setId(id); + carSensor.setConnectflag(connectflag); + carSensor.setIp(ip); + carSensor.setPort(port); + carSensor.setLane(lane); + carSensor.setLanelength(lanelength); + carSensor.setLaneflag(laneflag); + carSensor.setLaneweight1(laneweight1); + carSensor.setLaneweight2(laneweight2); + carSensor.setLaneweight3(laneweight3); + carSensor.setLaneweight4(laneweight4); + carSensor.setLaneweight5(laneweight5); + carSensor.setLaneweight6(laneweight6); + carSensor.setLaneweight7(laneweight7); + carSensor.setLaneweight8(laneweight8); + carSensor.setLine(carCheckSensorSet.getInt("line")); + + int floorNo = carCheckSensorSet.getInt("floorNo"); + List leftFloorNos = Arrays.asList(1,3,4,5,6,7,8,9,10,11); + List rightFloorNos = Arrays.asList(2,101,102,103,104,105,106,107,108,109); + if (leftFloorNos.contains(floorNo)) { + carSensor.setLaneMark("left"); + } else if (rightFloorNos.contains(floorNo)) { + carSensor.setLaneMark("right"); + } + + sensorInfoList.add(carSensor); + } + } + return sensorInfoList; + } + + /** + * 启动socket连接线程 + * @param carSensor + */ + private void addThread(CarSensor carSensor) { + String key = String.format("%s_%s_%s", carSensor.getComid(), carSensor.getIp(), carSensor.getPort()); + + // 设置重新连接,将前一个连接断开 + if (threadMap.get(key) != null) { + Thread thread = threadMap.get(key); + thread.interrupt(); + } + + Thread thread = connectSocketTask(carSensor); + threadMap.put(key, thread); + LOGGER.info(String.format("新增--------------车检器服务器 socket 连接,ip:%s,port:%s", carSensor.getIp(), carSensor.getPort())); + + // 更新传感器连接标识 + String connectFlagSql = "update sensors set connectflag = 0 where id = " + carSensor.getId(); + SQLHelper.ExecSql(connectFlagSql); + + } + + /** + * 更新socket连接线程 + * @param carSensor + */ + private void updateThread(CarSensor carSensor) { +// this.removeThread(carSensor); + this.addThread(carSensor); + } + + /** + * 停止socket连接线程 + * @param key + */ + private void removeThread(String key) { + String[] keyArray = key.split("_"); + String comid = keyArray[0]; + String ip = keyArray[1]; + String port = keyArray[2]; + LOGGER.info(String.format("删除--------------车检器服务器 socket 连接,comid: %s,ip:%s,port:%s", comid, ip, port)); + + Thread thread = threadMap.get(key); + thread.interrupt(); + threadMap.remove(key); + } + + private Thread connectSocketTask(CarSensor carSensor) { + Thread thread = new Thread(){ + @Override + public void run() { + connectSocket(carSensor); + } + }; + thread.start(); + return thread; + } + + private void connectSocket(CarSensor carSensor) { + Socket socket = null; + InetSocketAddress socketAddress = null; + try { + String ip = carSensor.getIp(); + int port = Integer.valueOf(carSensor.getPort()); +// socket = new Socket(ip, port); + LocalDateTime lastSocketTime = LocalDateTime.now(); + while (!Thread.currentThread().isInterrupted()) { + try { +// try { +// Thread.sleep(50); +// } catch (Exception e) { +// LOGGER.error("线程睡眠1s发生异常,error message:" + e.getMessage()); +// if (e instanceof InterruptedException) { +// Thread.currentThread().interrupt(); +// } +// } + +// if (socket == null || !socket.isConnected()) { + if (socket == null || socket.isClosed() || !socket.isConnected()) { + try { + // socket 重新连接,睡眠 3秒钟 + Thread.sleep(3 * 1000); + + socket = new Socket(); + socketAddress = new InetSocketAddress(ip, port); + socket.connect(socketAddress, 2 * 1000); + socket.setSoTimeout(3 * 1000); + LOGGER.info(String.format("车检器服务器 socket 连接成功,ip:%s,port:%s", ip, port)); + } catch (Exception e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + if (e instanceof SocketTimeoutException) { +// LOGGER.error(String.format("车检器服务器 socket 连接超时,ip:%s,port:%s", ip, port)); + } + } + + lastSocketTime = LocalDateTime.now(); + + // 更新传感器在线/离线标识 +// String connectFlagSql = "update sensors set online = 1 where id = " + carSensor.getId(); +// SQLHelper.ExecSql(connectFlagSql); + updateSensorOnlineStatus(carSensor, 1); + } + + // 判断socket服务器是否断开 +// try { +// socket.sendUrgentData(0XFF); +// } catch (Exception e) { +//// System.out.println(String.format("socket ip: %s, port: %s", ip, port)); +//// System.out.println(String.format("socket ip: %s, port: %s, isClosed : %s, isConnected : %s", +//// socket.getInetAddress().getHostAddress(), socket.getPort(), socket.isClosed(), socket.isConnected())); +//// e.printStackTrace(); +//// LOGGER.error("socket connect take error: {}", e.getMessage()); +// socket.close(); +// socket = null; +// +// updateSensorOnlineStatus(carSensor); +// } + + // 判断socket服务器是否假死(超时没有上报数据) + if (ChronoUnit.SECONDS.between(lastSocketTime, LocalDateTime.now()) > carCheckSocketTimeOut) { +// System.out.println("上次车检器socket通信时间:" + lastSocketTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); +// System.out.println("当前时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); + System.err.println(String.format("socket 服务器超过 5s 没上报数据,判定假死,socket ip: %s, port: %s", ip, port)); + + // socket 断开连接 + disConnectSocket(socket); + // 更新传感器状态 + updateSensorOnlineStatus(carSensor, 0); + // socket 断开连接,睡眠 3秒钟 + Thread.sleep(3 * 1000); + } + +// PrintWriter out = new PrintWriter(socket.getOutputStream()); +// out.flush(); + +// Scanner get = new Scanner(socket.getInputStream()); +// LOGGER.info(get.nextLine()); + +// System.out.println("socket status:" + !socket.isClosed()); + //接收信息 +// InputStream in = socket.getInputStream(); + // 如果 socket 连接正常,则解析数据报文 + if (socket != null && socket.isConnected() && !socket.isClosed()) { + try { + DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); + //获取输入流里面数据并存储数据 + byte[] b = new byte[dataInputStream.available()]; + if (b.length != 0) { + int numCount = dataInputStream.read(b); + String getHexStr = Common.GetHexStr(b, numCount); + System.out.println(String.format("来自车检器的数据,ip:%s,port:%s,data:%s ==========:", ip, port, getHexStr)); + lastSocketTime = LocalDateTime.now(); + +// String s = new String(b); +// System.out.println("来自车检器的数据:" + s); +// +// String[] dataArray = s.split(" "); + String[] dataArray = getHexStr.split("-"); + + int baseInfoIndex = 4; + int info2Index = 0; + int info3Index = 0; + int targetCount = 0; + int laneCount = 0; + boolean sendWebSocketMessage = false; + boolean verifyResult = false; + + // 校验 + // 总包校验 + int dataLength = Integer.parseInt(dataArray[3], 16); + int dataNum = 0; + int dataTotal = 0; + while (dataNum < dataLength) { + dataTotal += Integer.parseInt(dataArray[4 + dataNum], 16); +// System.out.println(dataArray[4 + dataNum]); + dataNum = dataNum + 1; + } + String dataHexString = Integer.toHexString(dataTotal); +// System.out.println(String.format("总包校验和:%s,报文中数据长度:%s", dataHexString.substring(dataHexString.length() - 2).toUpperCase(), dataArray[4 + dataLength])); + verifyResult = dataHexString.substring(dataHexString.length() - 2).toUpperCase().equals(dataArray[4 + dataLength]); + if (verifyResult == false) { +// System.err.println(String.format("总包校验不通过,总包校验和:%s,报文中数据长度:%s", dataHexString.substring(dataHexString.length() - 2).toUpperCase(), dataArray[4 + dataLength])); + } + + // 校验基础信息 + if (verifyResult && dataArray[4].equals("4A") && dataArray[5].equals("42")) { + int baseInfoLength = Integer.parseInt(dataArray[baseInfoIndex + 3], 16); + targetCount = Integer.parseInt(dataArray[baseInfoIndex + 13], 16); + laneCount = Integer.parseInt(dataArray[baseInfoIndex + 15], 16); +// System.out.println(String.format("基本信息模块,报文长度:%d,目标数:%d,车道数:%d", baseInfoLength, targetCount, laneCount)); + info2Index = baseInfoIndex + baseInfoLength; + + int num = 0; + int total = 0; + while (num < baseInfoLength - 1) { + total += Integer.parseInt(dataArray[baseInfoIndex + num], 16); +// System.out.println(dataArray[baseInfoIndex + num]); + num = num + 1; + } + String hexString = Integer.toHexString(total); + +// System.out.println(String.format("基础信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[baseInfoIndex + baseInfoLength - 1])); + verifyResult = hexString.substring(hexString.length() - 2).toUpperCase().equals(dataArray[baseInfoIndex + baseInfoLength - 1]); + + if (verifyResult == false) { + System.err.println(String.format("基础信息模块校验不通过,基础信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[baseInfoIndex + baseInfoLength - 1])); + } + } + // 校验目标信息 + if (verifyResult && dataArray[info2Index].equals("4D") && dataArray[info2Index + 1].equals("42")) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("目标信息模块,报文长度:" + baseInfoLength); + + int num = 0; + int total = 0; + while (num < baseInfoLength - 1) { + total += Integer.parseInt(dataArray[info2Index + num], 16); +// System.out.println(dataArray[info2Index + num]); + num = num + 1; + } + String hexString = Integer.toHexString(total); + +// System.out.println(String.format("目标信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info2Index + baseInfoLength - 1])); + verifyResult = hexString.substring(hexString.length() - 2).toUpperCase().equals(dataArray[info2Index + baseInfoLength - 1]); + + if (verifyResult == false) { + System.err.println(String.format("目标信息模块校验不通过,目标信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info2Index + baseInfoLength - 1])); + } + + info2Index = info2Index + baseInfoLength; + } + // 校验道路信息 + if (verifyResult && dataArray[info2Index].equals("44") && dataArray[info2Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("道路信息模块,报文长度:" + baseInfoLength); + + int num = 0; + int total = 0; + while (num < baseInfoLength - 1) { + total += Integer.parseInt(dataArray[info2Index + num], 16); +// System.out.println(dataArray[info2Index + num]); + num = num + 1; + } + String hexString = Integer.toHexString(total); + +// System.out.println(String.format("道路信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info2Index + baseInfoLength - 1])); + verifyResult = hexString.substring(hexString.length() - 2).toUpperCase().equals(dataArray[info2Index + baseInfoLength - 1]); + if (verifyResult == false) { + System.err.println(String.format("道路信息模块校验不通过,道路信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info2Index + baseInfoLength - 1])); + } + + info3Index = info2Index + baseInfoLength; + } + // 校验流量信息 + if (verifyResult && dataArray[info3Index].equals("4C") && dataArray[info3Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info3Index + 3], 16); +// System.out.println("流量信息模块,报文长度:" + baseInfoLength); + int num = 0; + int total = 0; + while (num < baseInfoLength - 1) { + total += Integer.parseInt(dataArray[info3Index + num], 16); +// System.out.println(dataArray[info3Index + num]); + num = num + 1; + } + String hexString = Integer.toHexString(total); + +// System.out.println(String.format("流量信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info3Index + baseInfoLength - 1])); + verifyResult = hexString.substring(hexString.length() - 2).toUpperCase().equals(dataArray[info3Index + baseInfoLength - 1]); + + if (verifyResult == false) { + System.err.println(String.format("流量信息模块校验不通过,流量信息模块校验和:%s,报文中数据长度:%s", hexString.substring(hexString.length() - 2).toUpperCase(), dataArray[info3Index + baseInfoLength - 1])); + } + } + + if (verifyResult) { + // 解析 + CarCheckInfo carCheckInfo = new CarCheckInfo(); + // 传感器信息 + SensorInfo sensorInfo = new SensorInfo(); + sensorInfo.setComid(carSensor.getComid()); + sensorInfo.setLane(carSensor.getLane()); + sensorInfo.setLaneMark(carSensor.getLaneMark()); + sensorInfo.setLaneflag(carSensor.getLaneflag()); + sensorInfo.setLanelength(carSensor.getLanelength()); + + List laneList = new ArrayList<>(); + for (int i = 0; i < carSensor.getLane(); i++) { + SensorInfo.LaneWeight laneWeight = new SensorInfo.LaneWeight(); + if (i == 0) { + laneWeight.setLaneweight((float)carSensor.getLaneweight1()); + } + if (i == 1) { + laneWeight.setLaneweight((float)carSensor.getLaneweight2()); + } + if (i == 2) { + laneWeight.setLaneweight((float)carSensor.getLaneweight3()); + } + if (i == 3) { + laneWeight.setLaneweight((float)carSensor.getLaneweight4()); + } + if (i == 4) { + laneWeight.setLaneweight((float)carSensor.getLaneweight5()); + } + if (i == 5) { + laneWeight.setLaneweight((float)carSensor.getLaneweight6()); + } + if (i == 6) { + laneWeight.setLaneweight((float)carSensor.getLaneweight7()); + } + if (i == 7) { + laneWeight.setLaneweight((float)carSensor.getLaneweight8()); + } + laneList.add(laneWeight); + } + sensorInfo.setLaneList(laneList); +// sensorInfo.setLaneweight1(carSensor.getLaneweight1()); +// sensorInfo.setLaneweight2(carSensor.getLaneweight2()); +// sensorInfo.setLaneweight3(carSensor.getLaneweight3()); +// sensorInfo.setLaneweight4(carSensor.getLaneweight4()); +// sensorInfo.setLaneweight5(carSensor.getLaneweight5()); +// sensorInfo.setLaneweight6(carSensor.getLaneweight6()); +// sensorInfo.setLaneweight7(carSensor.getLaneweight7()); +// sensorInfo.setLaneweight8(carSensor.getLaneweight8()); + sensorInfo.setLine(carSensor.getLine()); + carCheckInfo.setSensor(sensorInfo); + + String name = carSensor.getName(); + String comid = carSensor.getComid(); + String terminal = carSensor.getTerminal(); + + // 解析基本信息 + if (dataArray[4].equals("4A") && dataArray[5].equals("42")) { + int baseInfoLength = Integer.parseInt(dataArray[baseInfoIndex + 3], 16); + targetCount = Integer.parseInt(dataArray[baseInfoIndex + 12], 16); + laneCount = Integer.parseInt(dataArray[baseInfoIndex + 14], 16); +// System.out.println(String.format("基本信息模块,报文长度:%d,目标数:%d,车道数:%d", baseInfoLength, targetCount, laneCount)); + BaseInfo baseInfo = new BaseInfo(); + baseInfo.setLaneCount(laneCount); + baseInfo.setTrafficOutputFlag(Integer.parseInt(dataArray[baseInfoIndex + 16], 16)); + baseInfo.setGeneralTrafficIndication(Integer.parseInt(dataArray[baseInfoIndex + 20], 16)); + carCheckInfo.setBaseInfo(baseInfo); + info2Index = baseInfoIndex + baseInfoLength; + } + + // 解析目标信息 + List carInfoList = new ArrayList<>(); + if (dataArray[info2Index].equals("4D") && dataArray[info2Index + 1].equals("42")) { + info2Index = parseTargetInfo(dataArray, info2Index, carCheckInfo, carInfoList); + sendWebSocketMessage = true; + } else { + TargetInfo targetInfo = new TargetInfo(); + targetInfo.setValid(-1); + carCheckInfo.setTargetInfo(targetInfo); + } + + List carCheckDataList = new ArrayList<>(); + // 校验道路信息 + if (dataArray[info2Index].equals("44") && dataArray[info2Index + 1].equals("4C")) { + info3Index = parseLoadInfo(dataArray, info2Index, info3Index, laneCount, carCheckInfo, carCheckDataList); + sendWebSocketMessage = true; + } else { + LoadInfo loadInfo = new LoadInfo(); + loadInfo.setValid(-1); + carCheckInfo.setLoadInfo(loadInfo); + } + + // 解析流量信息 + if (dataArray[info3Index].equals("4C") && dataArray[info3Index + 1].equals("4C")) { + parseFlowInfo(name, comid, terminal, dataArray, info3Index, laneCount, carCheckInfo, + carInfoList, carCheckDataList); + } else { + FlowInfo flowInfo = new FlowInfo(); + flowInfo.setValid(-1); + carCheckInfo.setFlowInfo(flowInfo); + } + + // websocket 发送报文到前端 + if (sendWebSocketMessage) { + carCheckInfo.setCommand("pushCarCheckInfo"); +// System.out.println("websocket 报文:" + JSON.toJSONString(carCheckInfo)); + SocketServer.sendMessage(JSON.toJSONString(carCheckInfo)); + } + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + LOGGER.error(String.format("车检器 socket 服务端连接断开,ip:%s,port:%s ----------", ip, port)); + LOGGER.error("socket isConnected:{}, isClosed:{}", socket.isConnected(), socket.isClosed()); + } + } + + } catch (Exception e) { + LOGGER.error("socket connect task error: {}", e.getMessage()); + LOGGER.info(String.format("车检器 socket 服务端连接断开,ip:%s,port:%s", ip, port)); + updateSensorOnlineStatus(carSensor, 0); + +// socket.close(); +// System.out.println(String.format("socket ip: %s, port: %s, isClosed : %s, isConnected : %s", +// socket.getInetAddress().getHostAddress(), socket.getPort(), socket.isClosed(), socket.isConnected())); + + e.printStackTrace(); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + updateSensorOnlineStatus(carSensor, 0); + + System.out.println("err socket: " + socket.isClosed() + "|" + socket.isConnected()); + e.printStackTrace(); + } finally { + try { + disConnectSocket(socket); + } catch (IOException e) { + System.out.println("socket 连接关闭异常,error msg:" + e.getMessage()); + e.printStackTrace(); + } + } + } + + private void disConnectSocket(Socket socket) throws IOException { + if (socket != null) { +// socket.shutdownInput(); + socket.close(); + socket = null; + } + } + + private void updateSensorOnlineStatus(CarSensor carSensor, int online) { + // 更新传感器在线/离线标识 + String connectFlagSql = "update sensors set online = " + online + " where id = " + carSensor.getId() + " and online != " + online; + SQLHelper.ExecSql(connectFlagSql); + } + + private int parseTargetInfo(String[] dataArray, int info2Index, CarCheckInfo carCheckInfo, + List carInfoList) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("目标信息模块,报文长度:" + baseInfoLength); + + TargetInfo targetInfo = new TargetInfo(); + List targetList = new ArrayList<>(); + for (int k = 0; k < 1; k++) { + int index = info2Index + 3 + k * 29; + CarInfo carInfo = new CarInfo(); + carInfo.setLaneNumber(Integer.parseInt(dataArray[index + 9], 16)); + carInfo.setyDistance(Integer.parseInt(dataArray[index + 5] + dataArray[index + 6], 16)); + carInfo.setxDistance(Integer.parseInt(dataArray[index + 7] + dataArray[index + 8], 16)); + carInfo.setyFlow(Integer.parseInt(dataArray[index + 9] + dataArray[index + 10], 16)); + carInfo.setxFlow(Integer.parseInt(dataArray[index + 17] + dataArray[index + 18], 16)); + carInfoList.add(carInfo); + + // 目标信息 + TargetInfo.Target target = new TargetInfo.Target(); + +// System.out.println("十六进制:" + dataArray[index + 6] + dataArray[index + 5]); +// System.out.println("十六进制转化为二进制:" + Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16))); +// System.out.println((byte)Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2)); +// float i = (byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2); +// System.out.println("i: " + ((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2))) / 10); +// System.out.println("二进制转十进制取反:" + ~Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2)); +// System.out.println("二进制取反" + Integer.toBinaryString(~Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2))); + + target.setTargetNum(Integer.parseInt(dataArray[index + 1], 16)); + target.setyDistance(convert(dataArray, index + 2, index + 3).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + target.setxDistance(convert(dataArray, index + 4, index + 5).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + target.setyFlow(convert(dataArray, index + 6, index + 7).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + int targetType = Integer.parseInt(dataArray[index + 8], 16); + target.setTargetType(targetType); + target.setLaneNum(Integer.parseInt(dataArray[index + 9], 16)); + target.setxFlow(convert(dataArray, index + 14, index + 15).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); +// target.setyDistance(convert(dataArray, index + 6, index + 5)); +// target.setxDistance(convert(dataArray, index + 8, index + 7)); +// target.setyFlow(convert(dataArray, index + 10, index + 9)); +// target.setxFlow(convert(dataArray, index + 18, index + 17)); +// target.setyDistance(Integer.parseInt(dataArray[index + 5] + dataArray[index + 6], 16)); +// target.setxDistance(Integer.parseInt(dataArray[index + 7] + dataArray[index + 8], 16)); +// target.setyFlow(Integer.parseInt(dataArray[index + 9] + dataArray[index + 10], 16)); +// target.setxFlow(Integer.parseInt(dataArray[index + 17] + dataArray[index + 18], 16)); + if (!Arrays.asList(1, 2).contains(targetType)) { + targetList.add(target); + } + } +// System.out.println(JSON.toJSONString(carInfoList)); + targetInfo.setValid(1); + + + targetInfo.setTargetList(targetList); + targetInfo.setTargetCount(targetList.size()); + carCheckInfo.setTargetInfo(targetInfo); + + info2Index = info2Index + baseInfoLength; + return info2Index; + } + + private BigDecimal convert(String[] dataArray, int index1, int index2) { + + String binaryStr = Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)); +// System.out.println("十六进制转化为二进制:" + StringUtils.leftPad(binaryStr, 16, "0")); +// System.out.println("数据:" + dataArray[index1] + dataArray[index2]); +// System.out.println("转化后结果:" + Float.toString(((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)), 2))) / 10)); +// System.out.println("整数:" + Integer.parseInt(binaryStr, 2)); +// System.out.println("binaryToDecimal:" + binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); +// // 正数 +// if (StringUtils.leftPad(binaryStr, 16, "0").startsWith("0")) { +// return new BigDecimal(Integer.parseInt(binaryStr, 2)); +// } else {// 负数 +// return new BigDecimal(Float.toString(((float)((byte) Integer.parseInt(binaryStr, 2))))); +// } + return new BigDecimal(binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); + } + + private BigDecimal convert(String[] dataArray, int index) { + + String binaryStr = Integer.toBinaryString(Integer.parseInt(dataArray[index], 16)); +// System.out.println("十六进制转化为二进制:" + StringUtils.leftPad(binaryStr, 16, "0")); +// System.out.println("数据:" + dataArray[index1] + dataArray[index2]); +// System.out.println("转化后结果:" + Float.toString(((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)), 2))) / 10)); +// System.out.println("整数:" + Integer.parseInt(binaryStr, 2)); +// // 正数 +// if (StringUtils.leftPad(binaryStr, 16, "0").startsWith("0")) { +// return new BigDecimal(Integer.parseInt(binaryStr, 2)); +// } else {// 负数 +// return new BigDecimal(Float.toString(((float)((byte) Integer.parseInt(binaryStr, 2))))); +// } + return new BigDecimal(binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); + } + + // 将带符号位的二进制字符串转换为十进制数 + private static long binaryToDecimal(String binaryString) { + // 判断符号位 + char sign = binaryString.charAt(0); + int signMultiplier = (sign == '1') ? -1 : 1; + + // 使用位运算计算十进制数值 + long decimalNumber = 0; + for (int i = 1; i < binaryString.length(); i++) { + int bitValue = binaryString.charAt(i) - '0'; + decimalNumber = (decimalNumber << 1) | bitValue; + } + + return signMultiplier * decimalNumber; + } + + // 补码转原码函数 + private static String complementToOriginal(String complementCode) { + // 检查输入的补码是否有效 + if (!isValidBinary(complementCode)) { + throw new IllegalArgumentException("Invalid binary complement code"); + } + + char signBit = complementCode.charAt(0); // 符号位 + StringBuilder originalCode = new StringBuilder(); + + // 如果是负数,则进行转换 + if (signBit == '1') { + // 反码:对补码取反(除了符号位) + for (int i = 1; i < complementCode.length(); i++) { + originalCode.append((complementCode.charAt(i) == '0') ? '1' : '0'); + } + + // 加1 + int carry = 1; + for (int i = originalCode.length() - 1; i >= 0; i--) { + int sum = (originalCode.charAt(i) - '0') + carry; + originalCode.setCharAt(i, (char) (sum % 2 + '0')); + carry = sum / 2; + } + } else { + // 如果是正数或零,原码即为补码 + originalCode.append(complementCode.substring(1)); + } + + // 加上符号位 + return signBit + originalCode.toString(); + } + + // 检查二进制字符串是否有效 + private static boolean isValidBinary(String binary) { + return binary.matches("[01]+"); + } + + private void parseFlowInfo(String name, String comid, String terminal, String[] dataArray, int info3Index, + int laneCount, CarCheckInfo carCheckInfo, List carInfoList, List carCheckDataList) { + List flowList = new ArrayList<>(); + FlowInfo flowInfo = new FlowInfo(); + if (dataArray[info3Index].equals("4C") && dataArray[info3Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info3Index + 3], 16); +// System.out.println("流量信息模块,报文长度:" + baseInfoLength); + + for (int i = 0; i < laneCount; i++) { + int index = info3Index + 3 + i * 27; + // 车道号 + int laneNumber = Integer.parseInt(dataArray[index + 1], 16); + CarCheckData carCheckData = carCheckDataList.stream().filter(data -> data.getLaneNumber() == laneNumber).findFirst().orElse(null); + + carCheckData.setName(name); + carCheckData.setComid(comid); + carCheckData.setTerminal(terminal); + carCheckData.setMaxCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 2] + dataArray[index + 3], 16))); + carCheckData.setMaxCarAverageLanesflow(convert(dataArray, index + 4, index + 5)); + carCheckData.setMediumCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 6] + dataArray[index + 7], 16))); + carCheckData.setMediumCarAverageLanesflow(convert(dataArray, index + 8, index + 9)); + carCheckData.setMinCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 10] + dataArray[index + 11], 16))); + carCheckData.setMinCarAverageLanesflow(convert(dataArray, index + 12, index + 13)); + carCheckData.setLocomotiveLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 14] + dataArray[index + 15], 16))); + carCheckData.setLocomotiveAverageLanesflow(convert(dataArray, index + 16, index + 17)); + carCheckData.setMotorVehicleAverageLanesflow(convert(dataArray, index + 18, index + 19)); + carCheckData.setLaneOccupancy(convert(dataArray, index + 21)); + carCheckData.setTimeOccupancy(convert(dataArray, index + 23)); + carCheckData.setAverageTravelTime(convert(dataArray, index + 25)); + carCheckData.setAverageTravelDistance(convert(dataArray, index + 27)); + + CarInfo carInfo = carInfoList.stream().filter(data -> data.getLaneNumber() == laneNumber).findFirst().orElse(null); + if (carInfo != null) { + carCheckData.setxDistance(carInfo.getxDistance()); + carCheckData.setyDistance(carInfo.getyDistance()); + carCheckData.setxFlow(carInfo.getxFlow()); + carCheckData.setyFlow(carInfo.getyFlow()); + } + + // 流量信息 + FlowInfo.Flow flow = new FlowInfo.Flow(); + flow.setTerminal(terminal); + flow.setLaneNumber(laneNumber); + flow.setMaxCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 2] + dataArray[index + 3], 16))); + flow.setMaxCarAverageLanesflow(convert(dataArray, index + 4, index + 5)); + flow.setMediumCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 6] + dataArray[index + 7], 16))); + flow.setMediumCarAverageLanesflow(convert(dataArray, index + 8, index + 9)); + flow.setMinCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 10] + dataArray[index + 11], 16))); + flow.setMinCarAverageLanesflow(convert(dataArray, index + 12, index + 13)); + flow.setLocomotiveLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 14] + dataArray[index + 15], 16))); + flow.setLocomotiveAverageLanesflow(convert(dataArray, index + 16, index + 17)); + flow.setMotorVehicleAverageLanesflow(convert(dataArray, index + 18, index + 19)); + flow.setLaneOccupancy(convert(dataArray, index + 21)); + flow.setTimeOccupancy(convert(dataArray, index + 23)); + flow.setAverageTravelTime(convert(dataArray, index + 25)); + flow.setAverageTravelDistance(convert(dataArray, index + 27)); + flowList.add(flow); + } + +// System.out.println(JSON.toJSONString(carCheckDataList)); + flowInfo.setFlowList(flowList); + flowInfo.setValid(1); + flowInfo.setLaneCount(flowList.size()); + carCheckInfo.setFlowInfo(flowInfo); + + // 15分钟保存一次车流量数据判断 +// if (insertTime == null || ChronoUnit.MINUTES.between(insertTime, LocalDateTime.now()) >= carCheckSocketSaveInteval) { +// +// } + for (CarCheckData carCheckData : carCheckDataList) { + String insertSql = "INSERT INTO carcheckdata(sensorName, sensorComid, terminal, laneNumber, laneCongestion, maxCarLanesflow, maxCarAverageLanesflow, mediumCarLanesflow, mediumCarAverageLanesflow, " + + " minCarLanesflow, minCarAverageLanesflow, locomotiveLanesflow, locomotiveAverageLanesflow, motorVehicleAverageLanesflow, laneOccupancy, timeOccupancy, averageTravelTime, " + + " averageTravelDistance, writeTime) " + + " VALUES ('%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '%s')"; + SQLHelper.saveData(String.format(insertSql, carCheckData.getName(), carCheckData.getComid(), carCheckData.getTerminal(), carCheckData.getLaneNumber(), carCheckData.getLaneCongestion(), + carCheckData.getMaxCarLanesflow(), carCheckData.getMaxCarAverageLanesflow(), carCheckData.getMediumCarLanesflow(), carCheckData.getMediumCarAverageLanesflow(), + carCheckData.getMinCarLanesflow(), carCheckData.getMinCarAverageLanesflow(), carCheckData.getLocomotiveLanesflow(), carCheckData.getLocomotiveAverageLanesflow(), + carCheckData.getMotorVehicleAverageLanesflow(), carCheckData.getLaneOccupancy(), carCheckData.getTimeOccupancy(), carCheckData.getAverageTravelTime(), + carCheckData.getAverageTravelDistance(), LocalDateTime.now().toString())); + insertTime = LocalDateTime.now(); + } + + // 车流量总和 + BigDecimal flow = carCheckDataList.stream().map(e -> { + BigDecimal flowSum = e.getMaxCarLanesflow().add(e.getMediumCarLanesflow()).add(e.getMinCarLanesflow()); + return flowSum; + }).reduce(BigDecimal.ZERO, BigDecimal::add); + + String updateFlowSql = "update sensors set flow = " + flow + ", flowWriteTime = NOW() where comid = '" + comid + "'"; + SQLHelper.ExecSql(updateFlowSql); + } + } + + private int parseLoadInfo(String[] dataArray, int info2Index, int info3Index, int laneCount, + CarCheckInfo carCheckInfo, List carCheckDataList) { + LoadInfo loadInfo = new LoadInfo(); + if (dataArray[info2Index].equals("44") && dataArray[info2Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("道路信息模块,报文长度:" + baseInfoLength); + info3Index = info2Index + baseInfoLength; + + List loadList = new ArrayList<>(); + for (int j = 0; j < laneCount; j++) { + int index = info2Index + 3 + j * 4; + // 车道号 + int laneNumber = Integer.parseInt(dataArray[index + 1], 16); + CarCheckData carCheckData = new CarCheckData(); + carCheckData.setLaneNumber(laneNumber); + carCheckData.setLaneCongestion(Integer.parseInt(dataArray[index + 4], 16)); + carCheckDataList.add(carCheckData); + + // 道路信息 + LoadInfo.Load load = new LoadInfo.Load(); + load.setLaneNumber(laneNumber); + load.setLaneCongestion(Integer.parseInt(dataArray[index + 4], 16)); + loadList.add(load); + } + loadInfo.setValid(1); + loadInfo.setLoadList(loadList); + loadInfo.setLaneCount(loadList.size()); + carCheckInfo.setLoadInfo(loadInfo); + } + return info3Index; + } + + /** + * 两个字节转为十进制 + * @param data 十六进制低位 + * @param data 十六进制高位 + * @return + */ + public static int byteToInt(byte[] data){ + int deci = ((data[0] & 0xff)|(data[1] & 0xff)<<8); + return deci; + } + + + private class CarCheckData { + private String name; + private String comid; + private String terminal; + private int laneNumber; + private int laneCongestion; + private BigDecimal maxCarLanesflow; + private BigDecimal maxCarAverageLanesflow; + private BigDecimal mediumCarLanesflow; + private BigDecimal mediumCarAverageLanesflow; + private BigDecimal minCarLanesflow; + private BigDecimal minCarAverageLanesflow; + private BigDecimal locomotiveLanesflow; + private BigDecimal locomotiveAverageLanesflow; + private BigDecimal motorVehicleAverageLanesflow; + private BigDecimal laneOccupancy; + private BigDecimal timeOccupancy; + private BigDecimal averageTravelTime; + private BigDecimal averageTravelDistance; + private int xDistance; + private int yDistance; + private int xFlow; + private int yFlow; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getComid() { + return comid; + } + public void setComid(String comid) { + this.comid = comid; + } + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getLaneCongestion() { + return laneCongestion; + } + public void setLaneCongestion(int laneCongestion) { + this.laneCongestion = laneCongestion; + } + public BigDecimal getMaxCarLanesflow() { + return maxCarLanesflow; + } + public void setMaxCarLanesflow(BigDecimal maxCarLanesflow) { + this.maxCarLanesflow = maxCarLanesflow; + } + public BigDecimal getMaxCarAverageLanesflow() { + return maxCarAverageLanesflow; + } + public void setMaxCarAverageLanesflow(BigDecimal maxCarAverageLanesflow) { + this.maxCarAverageLanesflow = maxCarAverageLanesflow; + } + public BigDecimal getMediumCarLanesflow() { + return mediumCarLanesflow; + } + public void setMediumCarLanesflow(BigDecimal mediumCarLanesflow) { + this.mediumCarLanesflow = mediumCarLanesflow; + } + public BigDecimal getMediumCarAverageLanesflow() { + return mediumCarAverageLanesflow; + } + public void setMediumCarAverageLanesflow(BigDecimal mediumCarAverageLanesflow) { + this.mediumCarAverageLanesflow = mediumCarAverageLanesflow; + } + public BigDecimal getMinCarLanesflow() { + return minCarLanesflow; + } + public void setMinCarLanesflow(BigDecimal minCarLanesflow) { + this.minCarLanesflow = minCarLanesflow; + } + public BigDecimal getMinCarAverageLanesflow() { + return minCarAverageLanesflow; + } + public void setMinCarAverageLanesflow(BigDecimal minCarAverageLanesflow) { + this.minCarAverageLanesflow = minCarAverageLanesflow; + } + public BigDecimal getLocomotiveLanesflow() { + return locomotiveLanesflow; + } + public void setLocomotiveLanesflow(BigDecimal locomotiveLanesflow) { + this.locomotiveLanesflow = locomotiveLanesflow; + } + public BigDecimal getLocomotiveAverageLanesflow() { + return locomotiveAverageLanesflow; + } + public void setLocomotiveAverageLanesflow(BigDecimal locomotiveAverageLanesflow) { + this.locomotiveAverageLanesflow = locomotiveAverageLanesflow; + } + public BigDecimal getMotorVehicleAverageLanesflow() { + return motorVehicleAverageLanesflow; + } + public void setMotorVehicleAverageLanesflow(BigDecimal motorVehicleAverageLanesflow) { + this.motorVehicleAverageLanesflow = motorVehicleAverageLanesflow; + } + public BigDecimal getLaneOccupancy() { + return laneOccupancy; + } + public void setLaneOccupancy(BigDecimal laneOccupancy) { + this.laneOccupancy = laneOccupancy; + } + public BigDecimal getTimeOccupancy() { + return timeOccupancy; + } + public void setTimeOccupancy(BigDecimal timeOccupancy) { + this.timeOccupancy = timeOccupancy; + } + public BigDecimal getAverageTravelTime() { + return averageTravelTime; + } + public void setAverageTravelTime(BigDecimal averageTravelTime) { + this.averageTravelTime = averageTravelTime; + } + public BigDecimal getAverageTravelDistance() { + return averageTravelDistance; + } + public void setAverageTravelDistance(BigDecimal averageTravelDistance) { + this.averageTravelDistance = averageTravelDistance; + } + public int getxDistance() { + return xDistance; + } + public void setxDistance(int xDistance) { + this.xDistance = xDistance; + } + public int getyDistance() { + return yDistance; + } + public void setyDistance(int yDistance) { + this.yDistance = yDistance; + } + public int getxFlow() { + return xFlow; + } + public void setxFlow(int xFlow) { + this.xFlow = xFlow; + } + public int getyFlow() { + return yFlow; + } + public void setyFlow(int yFlow) { + this.yFlow = yFlow; + } + } + + public class CarInfo { + private int laneNumber; + private int xDistance; + private int yDistance; + private int xFlow; + private int yFlow; + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getxDistance() { + return xDistance; + } + public void setxDistance(int xDistance) { + this.xDistance = xDistance; + } + public int getyDistance() { + return yDistance; + } + public void setyDistance(int yDistance) { + this.yDistance = yDistance; + } + public int getxFlow() { + return xFlow; + } + public void setxFlow(int xFlow) { + this.xFlow = xFlow; + } + public int getyFlow() { + return yFlow; + } + public void setyFlow(int yFlow) { + this.yFlow = yFlow; + } + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/SocketServer.java b/carCheck/src/main/java/com/back/webSocket/SocketServer.java new file mode 100644 index 0000000..7a15ad0 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/SocketServer.java @@ -0,0 +1,277 @@ +package com.back.webSocket; + + +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.sql.ResultSet; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; + +import com.back.webSocket.bean.CarCheckInfo; +import com.back.webSocket.bean.LineInfo; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import com.back.jdbc.SQLHelper; + + + + +public class SocketServer extends WebSocketServer { + + public static final Logger LOGGER = LoggerFactory.getLogger(SocketServer.class); + + public SocketServer(int port) throws UnknownHostException { + super(new InetSocketAddress(port)); + } + + public SocketServer(InetSocketAddress address) { + super(address); + } + + public static Map map = new ConcurrentHashMap<>(); + public static Map connectMap = new ConcurrentHashMap<>(); + public static Map connectWaitMap = new ConcurrentHashMap<>(); + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("Welcome to the server!"); // This method sends a message to the new client +// broadcast("new connection: " + handshake.getResourceDescriptor()); // This method sends a message to all clients connected + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); +// System.out.println(clientIp + " entered the room!"); + map.put(clientIp, conn); + +// String projectId = null; +// String paramString = handshake.getResourceDescriptor().replace("?", "").replace("/", ""); +// if (StringUtils.isNoneEmpty(paramString)) { +// +// String[] params = paramString.split("&"); +// for (String param : params) { +// String[] kv = param.split("="); +// if (kv.length > 0) { +// String key = kv[0]; +// String value = kv[1]; +// +// +// if (key.equals("projectId")) { +// projectId = value; +// } +// } +// } +// +// } + + + LOGGER.info("{}, 客户端:{}, 连接 websocket 服务器成功", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), clientIp); + + // 获取运行参数 +// RunParams runParams = SystemParameter.GetPostParams(); +// if (runParams == null) { +// System.out.println("Database connection failed!"); +// } +// +// if (StringUtils.isNoneEmpty(projectId)) { +// String carCheckSocketIp = runParams.carCheckSocketIp; +// int carCheckSocketPort = runParams.carCheckSocketPort; +// try { +// new CarCheckSocket(carCheckSocketIp, carCheckSocketPort, Integer.valueOf(projectId)).connectCarCheckSocket(); +// } catch (IOException e) { +// LOGGER.error("websocket 连接失败,error message:{}", e.getMessage()); +// } +// } + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + System.out.println(String.format("%s, ip: %s, websocket 断开连接", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), clientIp)); + + if (connectMap.get(clientIp) != null) { + connectMap.remove(clientIp); + } + } + + @Override + public void onMessage(WebSocket conn, String message) { + +// broadcast(message); + + try { + if (message.contains("longitude") && message.contains("latitude") + && message.contains("leftaddr") && message.contains("rightaddr")) { + System.out.println("切换项目: " + message); + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + LineInfo lineInfo = JSONObject.parseObject(message, LineInfo.class); + Integer projectId = Integer.valueOf(lineInfo.getId()); + ResultSet resultSet = SQLHelper.ExecProcwCommands("SELECT * FROM line WHERE id = " + projectId); + ChangeTunnelProjectRep changeTunnelProjectRep = new ChangeTunnelProjectRep(); + changeTunnelProjectRep.setCommand("changetunnelproject"); + changeTunnelProjectRep.setProjectid(projectId); + if (resultSet != null && resultSet.next()) { + changeTunnelProjectRep.setSuccessed(true); + changeTunnelProjectRep.setMessage("切换隧道成功"); + + SocketBean socketBean = new SocketBean(); + socketBean.setConn(conn); + socketBean.setProjectId(projectId); + connectMap.put(clientIp, socketBean); + + connectWaitMap.put(clientIp, 0); + } else { + changeTunnelProjectRep.setSuccessed(false); + changeTunnelProjectRep.setMessage("项目不存在"); + } + System.out.println("切换项目: " + message); + conn.send(JSON.toJSONString(changeTunnelProjectRep)); + } else if (message.contains("heartbeatmessage")) { + System.out.println("ping message: " + message); + + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + connectWaitMap.put(clientIp, 0); + + Map map = new HashMap(); + map.put("command", "heartbeatmessage"); + map.put("successed", true); + + System.out.println(String.format("%s, ip:%s, pong message: %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")), clientIp, JSON.toJSONString(map))); + conn.send(JSON.toJSONString(map)); + } else { + conn.send(message); + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + if (conn != null) { + // some errors like port binding failed may not be assignable to a specific + // websocket + } + + } + + public static void sendMessage(String message) { + for (Map.Entry entry : map.entrySet()) { + String ip = entry.getKey(); + try { + WebSocket conn = entry.getValue(); + + if (connectMap.get(ip) != null) { + SocketBean socketBean = connectMap.get(ip); + int projectId = socketBean.getProjectId(); + + CarCheckInfo carCheckInfo = JSONObject.parseObject(message, CarCheckInfo.class); + int line = carCheckInfo.getSensor().getLine(); + + if (projectId == line && conn != null) { + conn.send(message); +// LOGGER.info("给客户端:{},发送消息:{}", ip, message); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + LOGGER.info("WebSocket发送报文到前端发生异常,前端IP:{},错误信息:{}", ip, e.getMessage()); + } + + } + } + + @Override + public void onStart() { + System.out.println("Server started!"); + setConnectionLostTimeout(0); + setConnectionLostTimeout(100); + + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + + System.out.println("connectWaitMap: " + JSON.toJSONString(connectWaitMap)); + for (Map.Entry entry : connectMap.entrySet()) { + String ip = entry.getKey(); + if (connectWaitMap.get(ip) != null) { + int waitCount = connectWaitMap.get(ip) + 1; + connectWaitMap.put(ip, waitCount); + + if (waitCount > 3) { +// WebsocketConnectInstance websocketConnectInstance = WebsocketConnectInstance.getInstance(); +// websocketConnectInstance.setRestart(true); + + if (connectMap.get(ip) != null) { + SocketBean socketBean = connectMap.get(ip); + WebSocket webSocket = socketBean.getConn(); + webSocket.close(); + } + } + } + } + } + }, 0, 1 * 60 * 1000); + } + + class SocketBean { + WebSocket conn; + int projectId; + public WebSocket getConn() { + return conn; + } + public void setConn(WebSocket conn) { + this.conn = conn; + } + public int getProjectId() { + return projectId; + } + public void setProjectId(int projectId) { + this.projectId = projectId; + } + } + + class ChangeTunnelProjectRep { + private String command; + private boolean successed; + private Integer projectid; + private String message; + public String getCommand() { + return command; + } + public void setCommand(String command) { + this.command = command; + } + public boolean isSuccessed() { + return successed; + } + public void setSuccessed(boolean successed) { + this.successed = successed; + } + public Integer getProjectid() { + return projectid; + } + public void setProjectid(Integer projectid) { + this.projectid = projectid; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + } + +} \ No newline at end of file diff --git a/carCheck/src/main/java/com/back/webSocket/bean/BaseInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/BaseInfo.java new file mode 100644 index 0000000..e4994f8 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/BaseInfo.java @@ -0,0 +1,27 @@ +package com.back.webSocket.bean; + +public class BaseInfo { + + private Integer laneCount; + private int trafficOutputFlag; + private int generalTrafficIndication; + public Integer getLaneCount() { + return laneCount; + } + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + public int getTrafficOutputFlag() { + return trafficOutputFlag; + } + public void setTrafficOutputFlag(int trafficOutputFlag) { + this.trafficOutputFlag = trafficOutputFlag; + } + public int getGeneralTrafficIndication() { + return generalTrafficIndication; + } + public void setGeneralTrafficIndication(int generalTrafficIndication) { + this.generalTrafficIndication = generalTrafficIndication; + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/CarCheckInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/CarCheckInfo.java new file mode 100644 index 0000000..210f3dc --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/CarCheckInfo.java @@ -0,0 +1,49 @@ +package com.back.webSocket.bean; + + +public class CarCheckInfo { + private String command; + private BaseInfo baseInfo; + private TargetInfo targetInfo; + public SensorInfo sensor; + private LoadInfo loadInfo; + public FlowInfo flowInfo; + + public String getCommand() { + return command; + } + public void setCommand(String command) { + this.command = command; + } + public TargetInfo getTargetInfo() { + return targetInfo; + } + public void setTargetInfo(TargetInfo targetInfo) { + this.targetInfo = targetInfo; + } + public SensorInfo getSensor() { + return sensor; + } + public void setSensor(SensorInfo sensor) { + this.sensor = sensor; + } + public LoadInfo getLoadInfo() { + return loadInfo; + } + public void setLoadInfo(LoadInfo loadInfo) { + this.loadInfo = loadInfo; + } + public FlowInfo getFlowInfo() { + return flowInfo; + } + public void setFlowInfo(FlowInfo flowInfo) { + this.flowInfo = flowInfo; + } + public BaseInfo getBaseInfo() { + return baseInfo; + } + public void setBaseInfo(BaseInfo baseInfo) { + this.baseInfo = baseInfo; + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/CarSensor.java b/carCheck/src/main/java/com/back/webSocket/bean/CarSensor.java new file mode 100644 index 0000000..4e2565a --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/CarSensor.java @@ -0,0 +1,106 @@ +package com.back.webSocket.bean; + +public class CarSensor extends SensorInfo { + + private int id; + private String name; + private String terminal; + private String ip; + private String port; + private int connectflag; + + public int laneweight1; + public int laneweight2; + public int laneweight3; + public int laneweight4; + public int laneweight5; + public int laneweight6; + public int laneweight7; + public int laneweight8; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public String getIp() { + return ip; + } + public void setIp(String ip) { + this.ip = ip; + } + public String getPort() { + return port; + } + public void setPort(String port) { + this.port = port; + } + public int getConnectflag() { + return connectflag; + } + public void setConnectflag(int connectflag) { + this.connectflag = connectflag; + } + public int getLaneweight1() { + return laneweight1; + } + public void setLaneweight1(int laneweight1) { + this.laneweight1 = laneweight1; + } + public int getLaneweight2() { + return laneweight2; + } + public void setLaneweight2(int laneweight2) { + this.laneweight2 = laneweight2; + } + public int getLaneweight3() { + return laneweight3; + } + public void setLaneweight3(int laneweight3) { + this.laneweight3 = laneweight3; + } + public int getLaneweight4() { + return laneweight4; + } + public void setLaneweight4(int laneweight4) { + this.laneweight4 = laneweight4; + } + public int getLaneweight5() { + return laneweight5; + } + public void setLaneweight5(int laneweight5) { + this.laneweight5 = laneweight5; + } + public int getLaneweight6() { + return laneweight6; + } + public void setLaneweight6(int laneweight6) { + this.laneweight6 = laneweight6; + } + public int getLaneweight7() { + return laneweight7; + } + public void setLaneweight7(int laneweight7) { + this.laneweight7 = laneweight7; + } + public int getLaneweight8() { + return laneweight8; + } + public void setLaneweight8(int laneweight8) { + this.laneweight8 = laneweight8; + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/FlowInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/FlowInfo.java new file mode 100644 index 0000000..7dbca9e --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/FlowInfo.java @@ -0,0 +1,154 @@ +package com.back.webSocket.bean; + +import java.math.BigDecimal; +import java.util.List; + +public class FlowInfo { + + private Integer valid; + private Integer laneCount; + private List flowList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public Integer getLaneCount() { + return laneCount; + } + + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + + public List getFlowList() { + return flowList; + } + + public void setFlowList(List flowList) { + this.flowList = flowList; + } + + public static class Flow { +// private String name; +// private String comid; + private String terminal; + private int laneNumber; +// private int laneCongestion; + private BigDecimal maxCarLanesflow; + private BigDecimal maxCarAverageLanesflow; + private BigDecimal mediumCarLanesflow; + private BigDecimal mediumCarAverageLanesflow; + private BigDecimal minCarLanesflow; + private BigDecimal minCarAverageLanesflow; + private BigDecimal locomotiveLanesflow; + private BigDecimal locomotiveAverageLanesflow; + private BigDecimal motorVehicleAverageLanesflow; + private BigDecimal laneOccupancy; + private BigDecimal timeOccupancy; + private BigDecimal averageTravelTime; + private BigDecimal averageTravelDistance; + + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } +// public int getLaneCongestion() { +// return laneCongestion; +// } +// public void setLaneCongestion(int laneCongestion) { +// this.laneCongestion = laneCongestion; +// } + public BigDecimal getMaxCarLanesflow() { + return maxCarLanesflow; + } + public void setMaxCarLanesflow(BigDecimal maxCarLanesflow) { + this.maxCarLanesflow = maxCarLanesflow; + } + public BigDecimal getMaxCarAverageLanesflow() { + return maxCarAverageLanesflow; + } + public void setMaxCarAverageLanesflow(BigDecimal maxCarAverageLanesflow) { + this.maxCarAverageLanesflow = maxCarAverageLanesflow; + } + public BigDecimal getMediumCarLanesflow() { + return mediumCarLanesflow; + } + public void setMediumCarLanesflow(BigDecimal mediumCarLanesflow) { + this.mediumCarLanesflow = mediumCarLanesflow; + } + public BigDecimal getMediumCarAverageLanesflow() { + return mediumCarAverageLanesflow; + } + public void setMediumCarAverageLanesflow(BigDecimal mediumCarAverageLanesflow) { + this.mediumCarAverageLanesflow = mediumCarAverageLanesflow; + } + public BigDecimal getMinCarLanesflow() { + return minCarLanesflow; + } + public void setMinCarLanesflow(BigDecimal minCarLanesflow) { + this.minCarLanesflow = minCarLanesflow; + } + public BigDecimal getMinCarAverageLanesflow() { + return minCarAverageLanesflow; + } + public void setMinCarAverageLanesflow(BigDecimal minCarAverageLanesflow) { + this.minCarAverageLanesflow = minCarAverageLanesflow; + } + public BigDecimal getLocomotiveLanesflow() { + return locomotiveLanesflow; + } + public void setLocomotiveLanesflow(BigDecimal locomotiveLanesflow) { + this.locomotiveLanesflow = locomotiveLanesflow; + } + public BigDecimal getLocomotiveAverageLanesflow() { + return locomotiveAverageLanesflow; + } + public void setLocomotiveAverageLanesflow(BigDecimal locomotiveAverageLanesflow) { + this.locomotiveAverageLanesflow = locomotiveAverageLanesflow; + } + public BigDecimal getMotorVehicleAverageLanesflow() { + return motorVehicleAverageLanesflow; + } + public void setMotorVehicleAverageLanesflow(BigDecimal motorVehicleAverageLanesflow) { + this.motorVehicleAverageLanesflow = motorVehicleAverageLanesflow; + } + public BigDecimal getLaneOccupancy() { + return laneOccupancy; + } + public void setLaneOccupancy(BigDecimal laneOccupancy) { + this.laneOccupancy = laneOccupancy; + } + public BigDecimal getTimeOccupancy() { + return timeOccupancy; + } + public void setTimeOccupancy(BigDecimal timeOccupancy) { + this.timeOccupancy = timeOccupancy; + } + public BigDecimal getAverageTravelTime() { + return averageTravelTime; + } + public void setAverageTravelTime(BigDecimal averageTravelTime) { + this.averageTravelTime = averageTravelTime; + } + public BigDecimal getAverageTravelDistance() { + return averageTravelDistance; + } + public void setAverageTravelDistance(BigDecimal averageTravelDistance) { + this.averageTravelDistance = averageTravelDistance; + } + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/LineInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/LineInfo.java new file mode 100644 index 0000000..0fa43a2 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/LineInfo.java @@ -0,0 +1,81 @@ +package com.back.webSocket.bean; + +public class LineInfo { + private String id; + private String name; + private String longitude; + private String latitude; + private String leftaddr; + private String rightaddr; + private String createtime; + private String username; + private String city; + private String remark; + private String createuser; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getLongitude() { + return longitude; + } + public void setLongitude(String longitude) { + this.longitude = longitude; + } + public String getLatitude() { + return latitude; + } + public void setLatitude(String latitude) { + this.latitude = latitude; + } + public String getLeftaddr() { + return leftaddr; + } + public void setLeftaddr(String leftaddr) { + this.leftaddr = leftaddr; + } + public String getRightaddr() { + return rightaddr; + } + public void setRightaddr(String rightaddr) { + this.rightaddr = rightaddr; + } + public String getCreatetime() { + return createtime; + } + public void setCreatetime(String createtime) { + this.createtime = createtime; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getCity() { + return city; + } + public void setCity(String city) { + this.city = city; + } + public String getRemark() { + return remark; + } + public void setRemark(String remark) { + this.remark = remark; + } + public String getCreateuser() { + return createuser; + } + public void setCreateuser(String createuser) { + this.createuser = createuser; + } +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/LoadInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/LoadInfo.java new file mode 100644 index 0000000..5baa792 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/LoadInfo.java @@ -0,0 +1,53 @@ +package com.back.webSocket.bean; + +import java.util.List; + +public class LoadInfo { + + private Integer valid; + private Integer laneCount; + private List loadList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public Integer getLaneCount() { + return laneCount; + } + + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + + public List getLoadList() { + return loadList; + } + + public void setLoadList(List loadList) { + this.loadList = loadList; + } + + public static class Load { + private int laneNumber; + private int laneCongestion; + + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getLaneCongestion() { + return laneCongestion; + } + public void setLaneCongestion(int laneCongestion) { + this.laneCongestion = laneCongestion; + } + } + +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/SensorInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/SensorInfo.java new file mode 100644 index 0000000..afc11b4 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/SensorInfo.java @@ -0,0 +1,125 @@ +package com.back.webSocket.bean; + +import java.util.List; + +public class SensorInfo { + private String comid; + public int lane; + public String laneflag; + public String laneMark; +// public int laneweight1; +// public int laneweight2; +// public int laneweight3; +// public int laneweight4; +// public int laneweight5; +// public int laneweight6; +// public int laneweight7; +// public int laneweight8; + public int lanelength; + public int line; + + public List laneList; + + public static class LaneWeight { + private float laneweight; + + public float getLaneweight() { + return laneweight; + } + + public void setLaneweight(float laneweight) { + this.laneweight = laneweight; + } + } + + public String getComid() { + return comid; + } + public void setComid(String comid) { + this.comid = comid; + } + public int getLane() { + return lane; + } + public void setLane(int lane) { + this.lane = lane; + } + public String getLaneflag() { + return laneflag; + } + public void setLaneflag(String laneflag) { + this.laneflag = laneflag; + } +// public int getLaneweight1() { +// return laneweight1; +// } +// public void setLaneweight1(int laneweight1) { +// this.laneweight1 = laneweight1; +// } +// public int getLaneweight2() { +// return laneweight2; +// } +// public void setLaneweight2(int laneweight2) { +// this.laneweight2 = laneweight2; +// } +// public int getLaneweight3() { +// return laneweight3; +// } +// public void setLaneweight3(int laneweight3) { +// this.laneweight3 = laneweight3; +// } +// public int getLaneweight4() { +// return laneweight4; +// } +// public void setLaneweight4(int laneweight4) { +// this.laneweight4 = laneweight4; +// } +// public int getLaneweight5() { +// return laneweight5; +// } +// public void setLaneweight5(int laneweight5) { +// this.laneweight5 = laneweight5; +// } +// public int getLaneweight6() { +// return laneweight6; +// } +// public void setLaneweight6(int laneweight6) { +// this.laneweight6 = laneweight6; +// } +// public int getLaneweight7() { +// return laneweight7; +// } +// public void setLaneweight7(int laneweight7) { +// this.laneweight7 = laneweight7; +// } +// public int getLaneweight8() { +// return laneweight8; +// } +// public void setLaneweight8(int laneweight8) { +// this.laneweight8 = laneweight8; +// } + public int getLanelength() { + return lanelength; + } + public void setLanelength(int lanelength) { + this.lanelength = lanelength; + } + public int getLine() { + return line; + } + public void setLine(int line) { + this.line = line; + } + public String getLaneMark() { + return laneMark; + } + public void setLaneMark(String laneMark) { + this.laneMark = laneMark; + } + public List getLaneList() { + return laneList; + } + public void setLaneList(List laneList) { + this.laneList = laneList; + } +} diff --git a/carCheck/src/main/java/com/back/webSocket/bean/TargetInfo.java b/carCheck/src/main/java/com/back/webSocket/bean/TargetInfo.java new file mode 100644 index 0000000..d876432 --- /dev/null +++ b/carCheck/src/main/java/com/back/webSocket/bean/TargetInfo.java @@ -0,0 +1,89 @@ +package com.back.webSocket.bean; + +import java.math.BigDecimal; +import java.util.List; + +public class TargetInfo { + + private Integer valid; + private int targetCount; + private List targetList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public int getTargetCount() { + return targetCount; + } + + public void setTargetCount(int targetCount) { + this.targetCount = targetCount; + } + + public List getTargetList() { + return targetList; + } + + public void setTargetList(List targetList) { + this.targetList = targetList; + } + + public static class Target { + private int targetNum; + private int targetType; + private int laneNum; + private BigDecimal xDistance; + private BigDecimal yDistance; + private BigDecimal xFlow; + private BigDecimal yFlow; + + public BigDecimal getxDistance() { + return xDistance; + } + public void setxDistance(BigDecimal xDistance) { + this.xDistance = xDistance; + } + public BigDecimal getyDistance() { + return yDistance; + } + public void setyDistance(BigDecimal yDistance) { + this.yDistance = yDistance; + } + public BigDecimal getxFlow() { + return xFlow; + } + public void setxFlow(BigDecimal xFlow) { + this.xFlow = xFlow; + } + public BigDecimal getyFlow() { + return yFlow; + } + public void setyFlow(BigDecimal yFlow) { + this.yFlow = yFlow; + } + public int getTargetNum() { + return targetNum; + } + public void setTargetNum(int targetNum) { + this.targetNum = targetNum; + } + public int getTargetType() { + return targetType; + } + public void setTargetType(int targetType) { + this.targetType = targetType; + } + public int getLaneNum() { + return laneNum; + } + public void setLaneNum(int laneNum) { + this.laneNum = laneNum; + } + } + +} diff --git a/carCheck/target/classes/META-INF/MANIFEST.MF b/carCheck/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..bd2d96f --- /dev/null +++ b/carCheck/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: Administrator +Build-Jdk: 1.8.0_351 +Created-By: Maven Integration for Eclipse + diff --git a/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.properties b/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.properties new file mode 100644 index 0000000..1559b58 --- /dev/null +++ b/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Jun 05 23:14:29 CST 2024 +version=0.0.1-SNAPSHOT +groupId=com.back +m2e.projectName=2-carCheck +m2e.projectLocation=D\:\\fyj_20240312\\processor\\carCheck +artifactId=carCheck diff --git a/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.xml b/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.xml new file mode 100644 index 0000000..d01e908 --- /dev/null +++ b/carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + carCheck + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/carCheckNew/conn.properties b/carCheckNew/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/carCheckNew/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/carCheckNew/pom.xml b/carCheckNew/pom.xml new file mode 100644 index 0000000..754b41c --- /dev/null +++ b/carCheckNew/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + carCheckNew + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/carCheckNew/src/main/java/com/back/instance/WebsocketConnectInstance.java b/carCheckNew/src/main/java/com/back/instance/WebsocketConnectInstance.java new file mode 100644 index 0000000..9c39e54 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/instance/WebsocketConnectInstance.java @@ -0,0 +1,24 @@ +package com.back.instance; + +public class WebsocketConnectInstance { + + public static WebsocketConnectInstance websocketConnectInstance = null; + + public static WebsocketConnectInstance getInstance() { + if (websocketConnectInstance == null) { + websocketConnectInstance = new WebsocketConnectInstance(); + } + return websocketConnectInstance; + } + + private boolean restart; + + public boolean isRestart() { + return restart; + } + + public void setRestart(boolean restart) { + this.restart = restart; + } + +} diff --git a/carCheckNew/src/main/java/com/back/main/MainProcess.java b/carCheckNew/src/main/java/com/back/main/MainProcess.java new file mode 100644 index 0000000..5934ce6 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/main/MainProcess.java @@ -0,0 +1,66 @@ +package com.back.main; + +import java.net.UnknownHostException; +import java.util.TimeZone; +import java.util.Timer; +import java.util.TimerTask; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.back.common.RunParams; +import com.back.instance.WebsocketConnectInstance; +import com.back.protocol.SystemParameter; +import com.back.webSocket.CarCheckSocket; +import com.back.webSocket.SocketServer; + +public class MainProcess { + + public static final Logger LOGGER = LoggerFactory.getLogger(MainProcess.class); + + public static void main(String[] args) { + + System.out.println("ver 1.2.11 2024-05-07 15");// 英文 + System.out.println(TimeZone.getDefault().getDisplayName()); + // 获取运行参数 + RunParams runParams = SystemParameter.GetPostParams(); + if (runParams == null) { + System.out.println("Database connection failed!"); + } + int websocketPort = runParams.websocketPort; + String carCheckSocketIp = runParams.carCheckSocketIp; + int carCheckSocketPort = runParams.carCheckSocketPort; + + // 车检器 + try { + try { + SocketServer socketServer = new SocketServer(websocketPort); + socketServer.start(); + + // 定时判断 websocket 是否假死(3分钟) + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + try { + WebsocketConnectInstance websocketConnectInstance = WebsocketConnectInstance.getInstance(); +// if (websocketConnectInstance.isRestart()) { +// socketServer.stop(); +// socketServer.start(); +// } + } catch (Exception e) { + // TODO Auto-generated catch block + // e.printStackTrace(); + System.err.println("socketServer 重启发生异常"); + } + } + }, 0, 1 * 1000); + + } catch (UnknownHostException e) { + LOGGER.error("websocket 连接失败,error message:{}", e.getMessage()); + } + new CarCheckSocket(carCheckSocketIp, carCheckSocketPort).connectCarCheckSocket(); + } catch (Exception e) { + LOGGER.error("车检器 socket 连接失败,error message:{}", e.getMessage()); + } + } +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/CarCheckSocket.java b/carCheckNew/src/main/java/com/back/webSocket/CarCheckSocket.java new file mode 100644 index 0000000..f9e8609 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/CarCheckSocket.java @@ -0,0 +1,1219 @@ +package com.back.webSocket; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.alibaba.fastjson.JSON; +import com.back.action.Log; +import com.back.common.Common; +import com.back.instance.WebsocketConnectInstance; +import com.back.jdbc.SQLHelper; +import com.back.protocol.SystemParameter; +import com.back.threadpool.ThreadPool; +import com.back.webSocket.CarCheckSocket.CarInfo; +import com.back.webSocket.bean.BaseInfo; +import com.back.webSocket.bean.CarCheckInfo; +import com.back.webSocket.bean.CarSensor; +import com.back.webSocket.bean.FlowInfo; +import com.back.webSocket.bean.FlowInfo.Flow; +import com.back.webSocket.bean.LoadInfo; +import com.back.webSocket.bean.LoadInfo.Load; +import com.back.webSocket.bean.SensorInfo; +import com.back.webSocket.bean.SensorInfo.LaneWeight; +import com.back.webSocket.bean.TargetInfo; + +public class CarCheckSocket { + + public static final Logger LOGGER = LoggerFactory.getLogger(CarCheckSocket.class); + + private String socketIp; + + private int port; + + LocalDateTime insertTime = null; + +// int num = 0; + + Socket socket = null; + + private static ThreadPool threadPool; + int threadsize = SystemParameter.runParams.threadsize; + String language = SystemParameter.runParams.language; + int carCheckSocketTimeOut = SystemParameter.runParams.carCheckSocketTimeOut / 1000; + int carCheckSocketSaveInteval = SystemParameter.runParams.carCheckSocketSaveInteval / 60; + + private ConcurrentHashMap threadMap = new ConcurrentHashMap<>(); + + public CarCheckSocket(String socketIp, int port) { + super(); + this.socketIp = socketIp; + this.port = port; + + threadPool = ThreadPool.getInstance(threadsize, language);// 创建线程池 + try { + Thread.sleep(500);// 休眠500毫秒,以便让线程池中的工作线程全部运行 + } catch (InterruptedException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public void connectCarCheckSocket() throws IOException { + try { + // 1. 前置机启动时,查询车检器集合 + String carCheckSensorSql = "select s.id, s.name, s.comid, s.terminal, s.floorNo, s.ip, s.port, s.lane, s.lanelength, " + + " s.laneflag, s.laneweight1, s.laneweight2, s.laneweight3, s.laneweight4, " + + " s.laneweight5, s.laneweight6, s.laneweight7, s.laneweight8, s.connectflag, s.productid, t.line, sp.ip spip, " + + " sp.port spport, sp.lane splane, sp.lanelength splanelength, sp.laneflag splaneflag, " + + " sp.laneweight1 splaneweight1, sp.laneweight2 splaneweight2, sp.laneweight3 splaneweight3, " + + " sp.laneweight4 splaneweight4, sp.laneweight5 splaneweight5, sp.laneweight6 splaneweight6, " + + " sp.laneweight7 splaneweight7, sp.laneweight8 splaneweight8 from sensors s " + + " left join sensorproduct sp on s.productid = sp.id " + + " left join terminals t on s.terminal = t.comid " + + " where ((s.productid is null and s.type = '0004' and s.ip is not null and s.port is not null) or " + + " (s.productid is not null and sp.devicetype = '0004' and sp.ip is not null and sp.port is not null)) "; + List sensorInfoList = selectSensor(carCheckSensorSql); + + System.out.println("查询-sensorInfoList: " + JSON.toJSONString(sensorInfoList)); + + for (CarSensor carSensor : sensorInfoList) { +// // 启动连接 socket 任务 + addThread(carSensor); + } + + System.out.println("第三方车检器服务器连接完成,threadMap: " + JSON.toJSONString(threadMap)); + + // 第三方车检器检测连接定时任务 + Timer carCheckTimer = new Timer(); + carCheckTimer.schedule(new TimerTask() { + + @Override + public void run() { + System.out.println(String.format("当前时间:%s,正在连接的第三方车检器服务器,IP、端口集合: %s", + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), + JSON.toJSONString(threadMap.keys()))); + + // 查询需要重新连接第三方传感器 + String sensorSql = "select s.id, s.name, s.comid, s.terminal, s.floorNo, s.ip, s.port, s.lane, s.lanelength, s.laneflag, " + + " s.laneweight1, s.laneweight2, s.laneweight3, s.laneweight4, s.laneweight5, s.laneweight6, s.laneweight7, s.laneweight8, " + + " s.connectflag, s.productid, t.line, sp.ip spip, sp.port spport, sp.lane splane, sp.lanelength splanelength, sp.laneflag splaneflag, " + + " sp.laneweight1 splaneweight1, sp.laneweight2 splaneweight2, sp.laneweight3 splaneweight3, sp.laneweight4 splaneweight4, " + + " sp.laneweight5 splaneweight5, sp.laneweight6 splaneweight6, sp.laneweight7 splaneweight7, sp.laneweight8 splaneweight8 " + + " from sensors s left join sensorproduct sp on s.productid = sp.id left join terminals t on s.terminal = t.comid " + + " where ((s.productid is null and s.type = '0004' and s.ip is not null and s.port is not null) or " + + " (s.productid is not null and sp.devicetype = '0004' and sp.ip is not null and sp.port is not null)) "; + try { + List selectSensor = selectSensor(sensorSql); + System.out.println("sensorInfoList: " + JSON.toJSONString(selectSensor)); + // 需要移除的 socket 连接 + List removeSocketConnectList = new ArrayList<>(); + for (Map.Entry entry : threadMap.entrySet()) { + String[] keyArray = entry.getKey().split("_"); + String comid = keyArray[0]; + String ip = keyArray[1]; + String port = keyArray[2]; + CarSensor carSensor = selectSensor.stream() + .filter(sensor -> sensor.getComid().equals(comid) + && sensor.getIp().equals(ip) + && sensor.getPort().equals(port)) + .findFirst().orElse(null); + if (carSensor == null) { + System.out.println("移除key" + entry.getKey()); + removeSocketConnectList.add(entry.getKey()); + } + } + + for (String key : removeSocketConnectList) { + removeThread(key); + } + + // 需要新增的 socket 连接 + List addSocketConnectList = selectSensor.stream().filter(sensor -> sensor.getConnectflag() == 1).collect(Collectors.toList()); + for (CarSensor carSensor : addSocketConnectList) { + addThread(carSensor); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + }, 30 * 1000, 3 * 60 * 1000); + } catch (Exception e) { + System.out.println("error msg: " + e.getMessage()); + e.printStackTrace(); + } + } + + private List selectSensor(String carCheckSensorSql) throws SQLException { + List sensorInfoList = new ArrayList<>(); + ResultSet carCheckSensorSet = SQLHelper.ExecProcwCommands(carCheckSensorSql); + if (carCheckSensorSet != null) { + while (carCheckSensorSet.next()) { + CarSensor carSensor = new CarSensor(); + carSensor.setName(carCheckSensorSet.getString("name")); + carSensor.setComid(carCheckSensorSet.getString("comid")); + carSensor.setTerminal(carCheckSensorSet.getString("terminal")); + + String ip; + String port; + int lane; + int lanelength; + String laneflag; + int laneweight1; + int laneweight2; + int laneweight3; + int laneweight4; + int laneweight5; + int laneweight6; + int laneweight7; + int laneweight8; + + int id = carCheckSensorSet.getInt("id"); + int connectflag = carCheckSensorSet.getInt("connectflag"); + String productid = carCheckSensorSet.getString("productid"); + if (StringUtils.isNotEmpty(productid)) { + ip = carCheckSensorSet.getString("spip"); + port = carCheckSensorSet.getString("spport"); + lane = carCheckSensorSet.getInt("splane"); + lanelength = carCheckSensorSet.getInt("splanelength"); + laneflag = carCheckSensorSet.getString("splaneflag"); + laneweight1 = carCheckSensorSet.getInt("splaneweight1"); + laneweight2 = carCheckSensorSet.getInt("splaneweight2"); + laneweight3 = carCheckSensorSet.getInt("splaneweight3"); + laneweight4 = carCheckSensorSet.getInt("splaneweight4"); + laneweight5 = carCheckSensorSet.getInt("splaneweight5"); + laneweight6 = carCheckSensorSet.getInt("splaneweight6"); + laneweight7 = carCheckSensorSet.getInt("splaneweight7"); + laneweight8 = carCheckSensorSet.getInt("splaneweight8"); + + } else { + ip = carCheckSensorSet.getString("ip"); + port = carCheckSensorSet.getString("port"); + lane = carCheckSensorSet.getInt("lane"); + lanelength = carCheckSensorSet.getInt("lanelength"); + laneflag = carCheckSensorSet.getString("laneflag"); + laneweight1 = carCheckSensorSet.getInt("laneweight1"); + laneweight2 = carCheckSensorSet.getInt("laneweight2"); + laneweight3 = carCheckSensorSet.getInt("laneweight3"); + laneweight4 = carCheckSensorSet.getInt("laneweight4"); + laneweight5 = carCheckSensorSet.getInt("laneweight5"); + laneweight6 = carCheckSensorSet.getInt("laneweight6"); + laneweight7 = carCheckSensorSet.getInt("laneweight7"); + laneweight8 = carCheckSensorSet.getInt("laneweight8"); + + } + carSensor.setId(id); + carSensor.setConnectflag(connectflag); + carSensor.setIp(ip); + carSensor.setPort(port); + carSensor.setLane(lane); + carSensor.setLanelength(lanelength); + carSensor.setLaneflag(laneflag); + carSensor.setLaneweight1(laneweight1); + carSensor.setLaneweight2(laneweight2); + carSensor.setLaneweight3(laneweight3); + carSensor.setLaneweight4(laneweight4); + carSensor.setLaneweight5(laneweight5); + carSensor.setLaneweight6(laneweight6); + carSensor.setLaneweight7(laneweight7); + carSensor.setLaneweight8(laneweight8); + carSensor.setLine(carCheckSensorSet.getInt("line")); + + int floorNo = carCheckSensorSet.getInt("floorNo"); + List leftFloorNos = Arrays.asList(1,3,4,5,6,7,8,9,10,11); + List rightFloorNos = Arrays.asList(2,101,102,103,104,105,106,107,108,109); + if (leftFloorNos.contains(floorNo)) { + carSensor.setLaneMark("left"); + } else if (rightFloorNos.contains(floorNo)) { + carSensor.setLaneMark("right"); + } + + sensorInfoList.add(carSensor); + } + } + return sensorInfoList; + } + + /** + * 启动socket连接线程 + * @param carSensor + */ + private void addThread(CarSensor carSensor) { + String key = String.format("%s_%s_%s", carSensor.getComid(), carSensor.getIp(), carSensor.getPort()); + + // 设置重新连接,将前一个连接断开 + if (threadMap.get(key) != null) { + Thread thread = threadMap.get(key); + thread.interrupt(); + } + + Thread thread = connectSocketTask(carSensor); + threadMap.put(key, thread); + LOGGER.info(String.format("新增--------------车检器服务器 socket 连接,ip:%s,port:%s", carSensor.getIp(), carSensor.getPort())); + + // 更新传感器连接标识 + String connectFlagSql = "update sensors set connectflag = 0 where id = " + carSensor.getId(); + SQLHelper.ExecSql(connectFlagSql); + + } + + /** + * 更新socket连接线程 + * @param key + */ + private void updateThread(CarSensor carSensor) { +// this.removeThread(carSensor); + this.addThread(carSensor); + } + + /** + * 停止socket连接线程 + * @param key + */ + private void removeThread(String key) { + String[] keyArray = key.split("_"); + String comid = keyArray[0]; + String ip = keyArray[1]; + String port = keyArray[2]; + LOGGER.info(String.format("删除--------------车检器服务器 socket 连接,comid: %s,ip:%s,port:%s", comid, ip, port)); + + Thread thread = threadMap.get(key); + thread.interrupt(); + threadMap.remove(key); + } + + private Thread connectSocketTask(CarSensor carSensor) { + Thread thread = new Thread(){ + @Override + public void run() { + connectSocket(carSensor); + } + }; + thread.start(); + return thread; + } + + private void connectSocket(CarSensor carSensor) { + +// Timer carCheckTimer1 = new Timer(); +// carCheckTimer1.schedule(new TimerTask() { +// @Override +// public void run() { +// socketHandle(carSensor); +// } +// }, 0, 60 * 1000); + socketHandle(carSensor); + +// finally { +// try { +// disConnectSocket(socket); +// } catch (IOException e) { +// System.out.println("socket 连接关闭异常,error msg:" + e.getMessage()); +// e.printStackTrace(); +// } +// } + } + + private void socketHandle(CarSensor carSensor) { + InetSocketAddress socketAddress = null; +// int online = 0; + + try { + String ip = carSensor.getIp(); + int port = Integer.valueOf(carSensor.getPort()); + // socket = new Socket(ip, port); + //ip = "127.0.0.1";port = 8880; + LocalDateTime lastSocketTime = LocalDateTime.now(); + while (!Thread.currentThread().isInterrupted()) { + try { + if (socket == null || socket.isClosed() || !socket.isConnected()) { + try { + // socket 重新连接,睡眠 3秒钟 + Thread.sleep(3 * 1000); + socket = new Socket(); + socketAddress = new InetSocketAddress(ip, port); + socket.connect(socketAddress, 2 * 1000); +// socket.setSoTimeout(90 * 1000); + System.out.println(String.format("车检器服务器 socket 连接成功,ip:%s,port:%s", ip, port)); + // 更新传感器在线/离线标识 + updateSensorOnlineStatus(carSensor, 1); + } catch (Exception e) { + // TODO Auto-generated catch block + // e.printStackTrace(); + if (e instanceof SocketTimeoutException) { + LOGGER.error(String.format("车检器服务器 socket 连接超时,ip:%s,port:%s", ip, port)); + } + } + + lastSocketTime = LocalDateTime.now(); + //发送信息 + //[57,31,41,08,01,00,00,D2]; +// send(socket); + } else { + //发送信息 + //[57,31,41,08,01,00,00,D2]; +// send(socket); + } + + // 判断socket服务器是否假死(超时没有上报数据) + if (ChronoUnit.SECONDS.between(lastSocketTime, LocalDateTime.now()) >= carCheckSocketTimeOut) { +// System.out.println("上次车检器socket通信时间:" + lastSocketTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); +// System.out.println("当前时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); + System.err.println(String.format("socket 服务器超过 5s 没上报数据,判定假死,socket ip: %s, port: %s", ip, port)); + + // socket 断开连接 + disConnectSocket(socket); + // 更新传感器状态 + updateSensorOnlineStatus(carSensor, 0); + // socket 断开连接,睡眠 3秒钟 + Thread.sleep(3 * 1000); + } + +// PrintWriter out = new PrintWriter(socket.getOutputStream()); +// out.flush(); +// Scanner get = new Scanner(socket.getInputStream()); +// LOGGER.info(get.nextLine()); +// System.out.println("socket status:" + !socket.isClosed()); + + //while (!Thread.currentThread().isInterrupted()) { + // 如果 socket 连接正常,则解析数据报文 + if (socket != null && socket.isConnected() && !socket.isClosed()) { + +// send(socket); + try { + //接收信息 + DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); + //获取输入流里面数据并存储数据 + byte[] b = new byte[dataInputStream.available()]; + +// byte[] b = new byte[2048]; + + // 建立数据流 +// int numCount = new DataInputStream(socket.getInputStream()).read(b); + if (b.length != 0) { + int numCount = dataInputStream.read(b); + String getHexStr = Common.GetHexStr(b, numCount); + System.out.println(String.format("来自车检器的数据,ip:%s,port:%s,data:%s ==========:", ip, port, getHexStr)); + lastSocketTime = LocalDateTime.now(); + + String[] dataArray = getHexStr.split("-"); + // 校验报文 + boolean verifyResult = true; + //报文长度 + int dataLength = Integer.parseInt(dataArray[3], 16); + //车道数 + int laneCount = Integer.parseInt(dataArray[15], 16); + + //长度校验 +// if( dataLength != laneCount * 12 + 16 + 1 || dataArray.length != dataLength) { +// throw new Exception(); +// } + + //报文头校验 + if(!"57".equals(dataArray[0])) { + throw new Exception(); + } + if(!"31".equals(dataArray[1])) { + throw new Exception(); + } + //类型校验 + if(!"29".equals(dataArray[2])) { + throw new Exception(); + } + + //校验位校验 + int dataNum = 0; + int dataTotal = 0; + while (dataNum < dataLength-1) { + dataTotal += Integer.parseInt(dataArray[dataNum], 16); + dataNum = dataNum + 1; + } + String dataHexString = Integer.toHexString(dataTotal); + verifyResult = dataHexString.substring(dataHexString.length() - 2).toUpperCase().equals(dataArray[dataLength-1]); + //System.out.println("报文校验:"+verifyResult + ","+dataHexString.substring(dataHexString.length() - 2).toUpperCase() + "," +dataArray[dataLength-1]); + if (verifyResult) { +// num = 0; + CarCheckInfo carCheckInfo = new CarCheckInfo(); + + // 解析传感器信息 + SensorInfo sensorInfo = new SensorInfo(); + sensorInfo.setComid(carSensor.getComid()); + sensorInfo.setLane(carSensor.getLane()); + sensorInfo.setLaneMark(carSensor.getLaneMark()); + sensorInfo.setLaneflag(carSensor.getLaneflag()); + sensorInfo.setLanelength(carSensor.getLanelength()); + List laneList = new ArrayList<>(); + for (int i = 0; i < carSensor.getLane(); i++) { + SensorInfo.LaneWeight laneWeight = new LaneWeight(); + if (i == 0) { + laneWeight.setLaneweight((float)carSensor.getLaneweight1()); + } + if (i == 1) { + laneWeight.setLaneweight((float)carSensor.getLaneweight2()); + } + if (i == 2) { + laneWeight.setLaneweight((float)carSensor.getLaneweight3()); + } + if (i == 3) { + laneWeight.setLaneweight((float)carSensor.getLaneweight4()); + } + if (i == 4) { + laneWeight.setLaneweight((float)carSensor.getLaneweight5()); + } + if (i == 5) { + laneWeight.setLaneweight((float)carSensor.getLaneweight6()); + } + if (i == 6) { + laneWeight.setLaneweight((float)carSensor.getLaneweight7()); + } + if (i == 7) { + laneWeight.setLaneweight((float)carSensor.getLaneweight8()); + } + laneList.add(laneWeight); + } + sensorInfo.setLaneList(laneList); +// sensorInfo.setLaneweight1(carSensor.getLaneweight1()); +// sensorInfo.setLaneweight2(carSensor.getLaneweight2()); +// sensorInfo.setLaneweight3(carSensor.getLaneweight3()); +// sensorInfo.setLaneweight4(carSensor.getLaneweight4()); +// sensorInfo.setLaneweight5(carSensor.getLaneweight5()); +// sensorInfo.setLaneweight6(carSensor.getLaneweight6()); +// sensorInfo.setLaneweight7(carSensor.getLaneweight7()); +// sensorInfo.setLaneweight8(carSensor.getLaneweight8()); + sensorInfo.setLine(carSensor.getLine()); + carCheckInfo.setSensor(sensorInfo); + + + // 解析基本信息 + BaseInfo baseInfo = new BaseInfo(); + baseInfo.setLaneCount(laneCount); + baseInfo.setTrafficOutputFlag(1); + baseInfo.setGeneralTrafficIndication(0); + carCheckInfo.setBaseInfo(baseInfo); + + + // 解析目标信息 + TargetInfo targetInfo = new TargetInfo(); + targetInfo.setTargetCount(0); + targetInfo.setTargetList(null); + carCheckInfo.setTargetInfo(targetInfo); + + + // 校验道路信息 + LoadInfo loadInfo = new LoadInfo(); + List loadList = new ArrayList<>(); + Load load = null; + for(int i=0;i flowList = new ArrayList<>(); + Flow flow = null; + FlowInfo flowInfo = new FlowInfo(); + for(int i=0;i=3 ){ +// System.out.println(String.format("socket 服务器超过 3次未回复数据,判定假死,socket ip: %s, port: %s", ip, port)); +// +// num = 0; +// // socket 断开连接 +// disConnectSocket(socket); +// // 更新传感器状态 +// updateSensorOnlineStatus(carSensor, 0); +// } + + } + } + //} + } catch (Exception e) { + LOGGER.error("socket connect task error: {}", e.getMessage()); + LOGGER.info(String.format("车检器 socket 服务端连接断开,ip:%s,port:%s", ip, port)); + updateSensorOnlineStatus(carSensor, 0); + +// socket.close(); +// System.out.println(String.format("socket ip: %s, port: %s, isClosed : %s, isConnected : %s", +// socket.getInetAddress().getHostAddress(), socket.getPort(), socket.isClosed(), socket.isConnected())); + + e.printStackTrace(); + } + + } + } catch (Exception e) { + // TODO Auto-generated catch block + updateSensorOnlineStatus(carSensor, 0); + + System.out.println("err socket: " + socket.isClosed() + "|" + socket.isConnected()); + e.printStackTrace(); + } + } + + private void disConnectSocket(Socket socket) throws IOException { + if (socket != null) { +// socket.shutdownInput(); + socket.close(); + socket = null; + } + } + + private void updateSensorOnlineStatus(CarSensor carSensor, int online) { + // 更新传感器在线/离线标识 + String connectFlagSql = "update sensors set online = " + online + " where id = " + carSensor.getId() + " and online != " + online; + SQLHelper.ExecSql(connectFlagSql); + } + + private int parseTargetInfo(String[] dataArray, int info2Index, CarCheckInfo carCheckInfo, + List carInfoList) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("目标信息模块,报文长度:" + baseInfoLength); + + TargetInfo targetInfo = new TargetInfo(); + List targetList = new ArrayList<>(); + for (int k = 0; k < 1; k++) { + int index = info2Index + 3 + k * 29; + CarInfo carInfo = new CarInfo(); + carInfo.setLaneNumber(Integer.parseInt(dataArray[index + 9], 16)); + carInfo.setyDistance(Integer.parseInt(dataArray[index + 5] + dataArray[index + 6], 16)); + carInfo.setxDistance(Integer.parseInt(dataArray[index + 7] + dataArray[index + 8], 16)); + carInfo.setyFlow(Integer.parseInt(dataArray[index + 9] + dataArray[index + 10], 16)); + carInfo.setxFlow(Integer.parseInt(dataArray[index + 17] + dataArray[index + 18], 16)); + carInfoList.add(carInfo); + + // 目标信息 + TargetInfo.Target target = new TargetInfo.Target(); + +// System.out.println("十六进制:" + dataArray[index + 6] + dataArray[index + 5]); +// System.out.println("十六进制转化为二进制:" + Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16))); +// System.out.println((byte)Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2)); +// float i = (byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2); +// System.out.println("i: " + ((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2))) / 10); +// System.out.println("二进制转十进制取反:" + ~Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2)); +// System.out.println("二进制取反" + Integer.toBinaryString(~Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index + 6] + dataArray[index + 5], 16)), 2))); + + target.setTargetNum(Integer.parseInt(dataArray[index + 1], 16)); + target.setyDistance(convert(dataArray, index + 2, index + 3).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + target.setxDistance(convert(dataArray, index + 4, index + 5).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + target.setyFlow(convert(dataArray, index + 6, index + 7).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); + int targetType = Integer.parseInt(dataArray[index + 8], 16); + target.setTargetType(targetType); + target.setLaneNum(Integer.parseInt(dataArray[index + 9], 16)); + target.setxFlow(convert(dataArray, index + 14, index + 15).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP)); +// target.setyDistance(convert(dataArray, index + 6, index + 5)); +// target.setxDistance(convert(dataArray, index + 8, index + 7)); +// target.setyFlow(convert(dataArray, index + 10, index + 9)); +// target.setxFlow(convert(dataArray, index + 18, index + 17)); +// target.setyDistance(Integer.parseInt(dataArray[index + 5] + dataArray[index + 6], 16)); +// target.setxDistance(Integer.parseInt(dataArray[index + 7] + dataArray[index + 8], 16)); +// target.setyFlow(Integer.parseInt(dataArray[index + 9] + dataArray[index + 10], 16)); +// target.setxFlow(Integer.parseInt(dataArray[index + 17] + dataArray[index + 18], 16)); + if (!Arrays.asList(1, 2).contains(targetType)) { + targetList.add(target); + } + } +// System.out.println(JSON.toJSONString(carInfoList)); + targetInfo.setValid(1); + + + targetInfo.setTargetList(targetList); + targetInfo.setTargetCount(targetList.size()); + carCheckInfo.setTargetInfo(targetInfo); + + info2Index = info2Index + baseInfoLength; + return info2Index; + } + + private BigDecimal convert(String[] dataArray, int index1, int index2) { + + String binaryStr = Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)); +// System.out.println("十六进制转化为二进制:" + StringUtils.leftPad(binaryStr, 16, "0")); +// System.out.println("数据:" + dataArray[index1] + dataArray[index2]); +// System.out.println("转化后结果:" + Float.toString(((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)), 2))) / 10)); +// System.out.println("整数:" + Integer.parseInt(binaryStr, 2)); +// System.out.println("binaryToDecimal:" + binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); +// // 正数 +// if (StringUtils.leftPad(binaryStr, 16, "0").startsWith("0")) { +// return new BigDecimal(Integer.parseInt(binaryStr, 2)); +// } else {// 负数 +// return new BigDecimal(Float.toString(((float)((byte) Integer.parseInt(binaryStr, 2))))); +// } + return new BigDecimal(binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); + } + + private BigDecimal convert(String[] dataArray, int index) { + + String binaryStr = Integer.toBinaryString(Integer.parseInt(dataArray[index], 16)); +// System.out.println("十六进制转化为二进制:" + StringUtils.leftPad(binaryStr, 16, "0")); +// System.out.println("数据:" + dataArray[index1] + dataArray[index2]); +// System.out.println("转化后结果:" + Float.toString(((float)((byte) Integer.parseInt(Integer.toBinaryString(Integer.parseInt(dataArray[index1] + dataArray[index2], 16)), 2))) / 10)); +// System.out.println("整数:" + Integer.parseInt(binaryStr, 2)); +// // 正数 +// if (StringUtils.leftPad(binaryStr, 16, "0").startsWith("0")) { +// return new BigDecimal(Integer.parseInt(binaryStr, 2)); +// } else {// 负数 +// return new BigDecimal(Float.toString(((float)((byte) Integer.parseInt(binaryStr, 2))))); +// } + return new BigDecimal(binaryToDecimal(complementToOriginal(StringUtils.leftPad(binaryStr, 16, "0")))); + } + + // 将带符号位的二进制字符串转换为十进制数 + private static long binaryToDecimal(String binaryString) { + // 判断符号位 + char sign = binaryString.charAt(0); + int signMultiplier = (sign == '1') ? -1 : 1; + + // 使用位运算计算十进制数值 + long decimalNumber = 0; + for (int i = 1; i < binaryString.length(); i++) { + int bitValue = binaryString.charAt(i) - '0'; + decimalNumber = (decimalNumber << 1) | bitValue; + } + + return signMultiplier * decimalNumber; + } + + // 补码转原码函数 + private static String complementToOriginal(String complementCode) { + // 检查输入的补码是否有效 + if (!isValidBinary(complementCode)) { + throw new IllegalArgumentException("Invalid binary complement code"); + } + + char signBit = complementCode.charAt(0); // 符号位 + StringBuilder originalCode = new StringBuilder(); + + // 如果是负数,则进行转换 + if (signBit == '1') { + // 反码:对补码取反(除了符号位) + for (int i = 1; i < complementCode.length(); i++) { + originalCode.append((complementCode.charAt(i) == '0') ? '1' : '0'); + } + + // 加1 + int carry = 1; + for (int i = originalCode.length() - 1; i >= 0; i--) { + int sum = (originalCode.charAt(i) - '0') + carry; + originalCode.setCharAt(i, (char) (sum % 2 + '0')); + carry = sum / 2; + } + } else { + // 如果是正数或零,原码即为补码 + originalCode.append(complementCode.substring(1)); + } + + // 加上符号位 + return signBit + originalCode.toString(); + } + + // 检查二进制字符串是否有效 + private static boolean isValidBinary(String binary) { + return binary.matches("[01]+"); + } + + private void parseFlowInfo(String name, String comid, String terminal, String[] dataArray, int info3Index, + int laneCount, CarCheckInfo carCheckInfo, List carInfoList, List carCheckDataList) { + List flowList = new ArrayList<>(); + FlowInfo flowInfo = new FlowInfo(); + if (dataArray[info3Index].equals("4C") && dataArray[info3Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info3Index + 3], 16); +// System.out.println("流量信息模块,报文长度:" + baseInfoLength); + + for (int i = 0; i < laneCount; i++) { + int index = info3Index + 3 + i * 27; + // 车道号 + int laneNumber = Integer.parseInt(dataArray[index + 1], 16); +// CarCheckData carCheckData = carCheckDataList.stream().filter(data -> data.getLaneNumber() == laneNumber).findFirst().orElse(null); + CarCheckData carCheckData = new CarCheckData(); + carCheckData.setName(name); + carCheckData.setComid(comid); + carCheckData.setTerminal(terminal); + carCheckData.setMaxCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 2] + dataArray[index + 3], 16))); + carCheckData.setMaxCarAverageLanesflow(convert(dataArray, index + 4, index + 5)); + carCheckData.setMediumCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 6] + dataArray[index + 7], 16))); + carCheckData.setMediumCarAverageLanesflow(convert(dataArray, index + 8, index + 9)); + carCheckData.setMinCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 10] + dataArray[index + 11], 16))); + carCheckData.setMinCarAverageLanesflow(convert(dataArray, index + 12, index + 13)); + carCheckData.setLocomotiveLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 14] + dataArray[index + 15], 16))); + carCheckData.setLocomotiveAverageLanesflow(convert(dataArray, index + 16, index + 17)); + carCheckData.setMotorVehicleAverageLanesflow(convert(dataArray, index + 18, index + 19)); + carCheckData.setLaneOccupancy(convert(dataArray, index + 21)); + carCheckData.setTimeOccupancy(convert(dataArray, index + 23)); + carCheckData.setAverageTravelTime(convert(dataArray, index + 25)); + carCheckData.setAverageTravelDistance(convert(dataArray, index + 27)); + + CarInfo carInfo = carInfoList.stream().filter(data -> data.getLaneNumber() == laneNumber).findFirst().orElse(null); + if (carInfo != null) { + carCheckData.setxDistance(carInfo.getxDistance()); + carCheckData.setyDistance(carInfo.getyDistance()); + carCheckData.setxFlow(carInfo.getxFlow()); + carCheckData.setyFlow(carInfo.getyFlow()); + } + carCheckDataList.add(carCheckData); + + // 流量信息 + FlowInfo.Flow flow = new FlowInfo.Flow(); + flow.setTerminal(terminal); + flow.setLaneNumber(laneNumber); + flow.setMaxCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 2] + dataArray[index + 3], 16))); + flow.setMaxCarAverageLanesflow(convert(dataArray, index + 4, index + 5)); + flow.setMediumCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 6] + dataArray[index + 7], 16))); + flow.setMediumCarAverageLanesflow(convert(dataArray, index + 8, index + 9)); + flow.setMinCarLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 10] + dataArray[index + 11], 16))); + flow.setMinCarAverageLanesflow(convert(dataArray, index + 12, index + 13)); + flow.setLocomotiveLanesflow(new BigDecimal(Integer.parseInt(dataArray[index + 14] + dataArray[index + 15], 16))); + flow.setLocomotiveAverageLanesflow(convert(dataArray, index + 16, index + 17)); + flow.setMotorVehicleAverageLanesflow(convert(dataArray, index + 18, index + 19)); + flow.setLaneOccupancy(convert(dataArray, index + 21)); + flow.setTimeOccupancy(convert(dataArray, index + 23)); + flow.setAverageTravelTime(convert(dataArray, index + 25)); + flow.setAverageTravelDistance(convert(dataArray, index + 27)); + flowList.add(flow); + } + +// System.out.println(JSON.toJSONString(carCheckDataList)); + flowInfo.setFlowList(flowList); + flowInfo.setValid(1); + flowInfo.setLaneCount(flowList.size()); + carCheckInfo.setFlowInfo(flowInfo); + + // 15分钟保存一次车流量数据判断 +// if (insertTime == null || ChronoUnit.MINUTES.between(insertTime, LocalDateTime.now()) >= carCheckSocketSaveInteval) { +// +// } + for (CarCheckData carCheckData : carCheckDataList) { + String insertSql = "INSERT INTO carcheckdata(sensorName, sensorComid, terminal, laneNumber, laneCongestion, maxCarLanesflow, maxCarAverageLanesflow, mediumCarLanesflow, mediumCarAverageLanesflow, " + + " minCarLanesflow, minCarAverageLanesflow, locomotiveLanesflow, locomotiveAverageLanesflow, motorVehicleAverageLanesflow, laneOccupancy, timeOccupancy, averageTravelTime, " + + " averageTravelDistance, writeTime) " + + " VALUES ('%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, '%s')"; + SQLHelper.saveData(String.format(insertSql, carCheckData.getName(), carCheckData.getComid(), carCheckData.getTerminal(), carCheckData.getLaneNumber(), carCheckData.getLaneCongestion(), + carCheckData.getMaxCarLanesflow(), carCheckData.getMaxCarAverageLanesflow(), carCheckData.getMediumCarLanesflow(), carCheckData.getMediumCarAverageLanesflow(), + carCheckData.getMinCarLanesflow(), carCheckData.getMinCarAverageLanesflow(), carCheckData.getLocomotiveLanesflow(), carCheckData.getLocomotiveAverageLanesflow(), + carCheckData.getMotorVehicleAverageLanesflow(), carCheckData.getLaneOccupancy(), carCheckData.getTimeOccupancy(), carCheckData.getAverageTravelTime(), + carCheckData.getAverageTravelDistance(), LocalDateTime.now().toString())); + insertTime = LocalDateTime.now(); + } + + // 车流量总和 + BigDecimal flow = carCheckDataList.stream().map(e -> { + BigDecimal flowSum = e.getMaxCarLanesflow().add(e.getMediumCarLanesflow()).add(e.getMinCarLanesflow()); + return flowSum; + }).reduce(BigDecimal.ZERO, BigDecimal::add); + + String updateFlowSql = "update sensors set flow = " + flow + ", flowWriteTime = NOW() where comid = '" + comid + "'"; + SQLHelper.ExecSql(updateFlowSql); + } + } + + private int parseLoadInfo(String[] dataArray, int info2Index, int info3Index, int laneCount, + CarCheckInfo carCheckInfo, List carCheckDataList) { + LoadInfo loadInfo = new LoadInfo(); + if (dataArray[info2Index].equals("44") && dataArray[info2Index + 1].equals("4C")) { + int baseInfoLength = Integer.parseInt(dataArray[info2Index + 3], 16); +// System.out.println("道路信息模块,报文长度:" + baseInfoLength); + info3Index = info2Index + baseInfoLength; + + List loadList = new ArrayList<>(); + for (int j = 0; j < laneCount; j++) { + int index = info2Index + 3 + j * 5; + // 车道号 + int laneNumber = Integer.parseInt(dataArray[index + 1], 16); +// CarCheckData carCheckData = new CarCheckData(); +// carCheckData.setLaneNumber(laneNumber); +// carCheckData.setLaneCongestion(Integer.parseInt(dataArray[index + 4], 16)); +// carCheckDataList.add(carCheckData); + + // 道路信息 + LoadInfo.Load load = new Load(); + load.setLaneNumber(laneNumber); + load.setLaneCongestion(Integer.parseInt(dataArray[index + 4], 16)); + loadList.add(load); + } + loadInfo.setValid(1); + loadInfo.setLoadList(loadList); + loadInfo.setLaneCount(loadList.size()); + carCheckInfo.setLoadInfo(loadInfo); + } + return info3Index; + } + + /** + * 两个字节转为十进制 + * @param data[0] 十六进制低位 + * @param data[1] 十六进制高位 + * @return + */ + public static int byteToInt(byte[] data){ + int deci = ((data[0] & 0xff)|(data[1] & 0xff)<<8); + return deci; + } + + + private class CarCheckData { + private String name; + private String comid; + private String terminal; + private int laneNumber; + private int laneCongestion; + private BigDecimal maxCarLanesflow; + private BigDecimal maxCarAverageLanesflow; + private BigDecimal mediumCarLanesflow; + private BigDecimal mediumCarAverageLanesflow; + private BigDecimal minCarLanesflow; + private BigDecimal minCarAverageLanesflow; + private BigDecimal locomotiveLanesflow; + private BigDecimal locomotiveAverageLanesflow; + private BigDecimal motorVehicleAverageLanesflow; + private BigDecimal laneOccupancy; + private BigDecimal timeOccupancy; + private BigDecimal averageTravelTime; + private BigDecimal averageTravelDistance; + private int xDistance; + private int yDistance; + private int xFlow; + private int yFlow; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getComid() { + return comid; + } + public void setComid(String comid) { + this.comid = comid; + } + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getLaneCongestion() { + return laneCongestion; + } + public void setLaneCongestion(int laneCongestion) { + this.laneCongestion = laneCongestion; + } + public BigDecimal getMaxCarLanesflow() { + return maxCarLanesflow; + } + public void setMaxCarLanesflow(BigDecimal maxCarLanesflow) { + this.maxCarLanesflow = maxCarLanesflow; + } + public BigDecimal getMaxCarAverageLanesflow() { + return maxCarAverageLanesflow; + } + public void setMaxCarAverageLanesflow(BigDecimal maxCarAverageLanesflow) { + this.maxCarAverageLanesflow = maxCarAverageLanesflow; + } + public BigDecimal getMediumCarLanesflow() { + return mediumCarLanesflow; + } + public void setMediumCarLanesflow(BigDecimal mediumCarLanesflow) { + this.mediumCarLanesflow = mediumCarLanesflow; + } + public BigDecimal getMediumCarAverageLanesflow() { + return mediumCarAverageLanesflow; + } + public void setMediumCarAverageLanesflow(BigDecimal mediumCarAverageLanesflow) { + this.mediumCarAverageLanesflow = mediumCarAverageLanesflow; + } + public BigDecimal getMinCarLanesflow() { + return minCarLanesflow; + } + public void setMinCarLanesflow(BigDecimal minCarLanesflow) { + this.minCarLanesflow = minCarLanesflow; + } + public BigDecimal getMinCarAverageLanesflow() { + return minCarAverageLanesflow; + } + public void setMinCarAverageLanesflow(BigDecimal minCarAverageLanesflow) { + this.minCarAverageLanesflow = minCarAverageLanesflow; + } + public BigDecimal getLocomotiveLanesflow() { + return locomotiveLanesflow; + } + public void setLocomotiveLanesflow(BigDecimal locomotiveLanesflow) { + this.locomotiveLanesflow = locomotiveLanesflow; + } + public BigDecimal getLocomotiveAverageLanesflow() { + return locomotiveAverageLanesflow; + } + public void setLocomotiveAverageLanesflow(BigDecimal locomotiveAverageLanesflow) { + this.locomotiveAverageLanesflow = locomotiveAverageLanesflow; + } + public BigDecimal getMotorVehicleAverageLanesflow() { + return motorVehicleAverageLanesflow; + } + public void setMotorVehicleAverageLanesflow(BigDecimal motorVehicleAverageLanesflow) { + this.motorVehicleAverageLanesflow = motorVehicleAverageLanesflow; + } + public BigDecimal getLaneOccupancy() { + return laneOccupancy; + } + public void setLaneOccupancy(BigDecimal laneOccupancy) { + this.laneOccupancy = laneOccupancy; + } + public BigDecimal getTimeOccupancy() { + return timeOccupancy; + } + public void setTimeOccupancy(BigDecimal timeOccupancy) { + this.timeOccupancy = timeOccupancy; + } + public BigDecimal getAverageTravelTime() { + return averageTravelTime; + } + public void setAverageTravelTime(BigDecimal averageTravelTime) { + this.averageTravelTime = averageTravelTime; + } + public BigDecimal getAverageTravelDistance() { + return averageTravelDistance; + } + public void setAverageTravelDistance(BigDecimal averageTravelDistance) { + this.averageTravelDistance = averageTravelDistance; + } + public int getxDistance() { + return xDistance; + } + public void setxDistance(int xDistance) { + this.xDistance = xDistance; + } + public int getyDistance() { + return yDistance; + } + public void setyDistance(int yDistance) { + this.yDistance = yDistance; + } + public int getxFlow() { + return xFlow; + } + public void setxFlow(int xFlow) { + this.xFlow = xFlow; + } + public int getyFlow() { + return yFlow; + } + public void setyFlow(int yFlow) { + this.yFlow = yFlow; + } + } + + public class CarInfo { + private int laneNumber; + private int xDistance; + private int yDistance; + private int xFlow; + private int yFlow; + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getxDistance() { + return xDistance; + } + public void setxDistance(int xDistance) { + this.xDistance = xDistance; + } + public int getyDistance() { + return yDistance; + } + public void setyDistance(int yDistance) { + this.yDistance = yDistance; + } + public int getxFlow() { + return xFlow; + } + public void setxFlow(int xFlow) { + this.xFlow = xFlow; + } + public int getyFlow() { + return yFlow; + } + public void setyFlow(int yFlow) { + this.yFlow = yFlow; + } + } + + //发送报文 + public void send(Socket socket) { + try { + + String title = "W1"; + String s1 = String.format("%02X", (int) title.charAt(0)); + String s2 = String.format("%02X", (int) title.charAt(1)); + String s3 = dec2Hex("41",2); + String s4 = dec2Hex("8",2); + String s5 = dec2Hex("0",2); + String s6 = dec2Hex("0",2); + String s7 = dec2Hex("0",2); + int all = Integer.parseInt(s1, 16) + + Integer.parseInt(s2, 16) + + Integer.parseInt(s3, 16) + + Integer.parseInt(s4, 16) + + Integer.parseInt(s5, 16) + + Integer.parseInt(s6, 16) + + Integer.parseInt(s7, 16); + //String s8 = dec2Hex(all+"",2); + + OutputStream out = socket.getOutputStream(); + byte[] by = new byte[8]; + by[0] = 87; + by[1] = 49; + by[2] = 41; + by[3] = 8; + by[4] = 0; + by[5] = 0; + by[6] = 0; + by[7] = (byte) all; + out.write(by); + /* + out.write("W".getBytes()); + out.write("1".getBytes()); + out.write(41); + out.write(8); + out.write(0); + out.write(0); + out.write(0); + out.write(all);*/ + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static String dec2Hex(String dec, int len) { + if (dec == null || dec.equals("")) + dec = "0"; + String tempString = Long.toHexString(Long.parseLong(dec)); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + + public static void main(String[] args) { + + + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/SocketServer.java b/carCheckNew/src/main/java/com/back/webSocket/SocketServer.java new file mode 100644 index 0000000..7a15ad0 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/SocketServer.java @@ -0,0 +1,277 @@ +package com.back.webSocket; + + +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.sql.ResultSet; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; + +import com.back.webSocket.bean.CarCheckInfo; +import com.back.webSocket.bean.LineInfo; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import com.back.jdbc.SQLHelper; + + + + +public class SocketServer extends WebSocketServer { + + public static final Logger LOGGER = LoggerFactory.getLogger(SocketServer.class); + + public SocketServer(int port) throws UnknownHostException { + super(new InetSocketAddress(port)); + } + + public SocketServer(InetSocketAddress address) { + super(address); + } + + public static Map map = new ConcurrentHashMap<>(); + public static Map connectMap = new ConcurrentHashMap<>(); + public static Map connectWaitMap = new ConcurrentHashMap<>(); + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + conn.send("Welcome to the server!"); // This method sends a message to the new client +// broadcast("new connection: " + handshake.getResourceDescriptor()); // This method sends a message to all clients connected + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); +// System.out.println(clientIp + " entered the room!"); + map.put(clientIp, conn); + +// String projectId = null; +// String paramString = handshake.getResourceDescriptor().replace("?", "").replace("/", ""); +// if (StringUtils.isNoneEmpty(paramString)) { +// +// String[] params = paramString.split("&"); +// for (String param : params) { +// String[] kv = param.split("="); +// if (kv.length > 0) { +// String key = kv[0]; +// String value = kv[1]; +// +// +// if (key.equals("projectId")) { +// projectId = value; +// } +// } +// } +// +// } + + + LOGGER.info("{}, 客户端:{}, 连接 websocket 服务器成功", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), clientIp); + + // 获取运行参数 +// RunParams runParams = SystemParameter.GetPostParams(); +// if (runParams == null) { +// System.out.println("Database connection failed!"); +// } +// +// if (StringUtils.isNoneEmpty(projectId)) { +// String carCheckSocketIp = runParams.carCheckSocketIp; +// int carCheckSocketPort = runParams.carCheckSocketPort; +// try { +// new CarCheckSocket(carCheckSocketIp, carCheckSocketPort, Integer.valueOf(projectId)).connectCarCheckSocket(); +// } catch (IOException e) { +// LOGGER.error("websocket 连接失败,error message:{}", e.getMessage()); +// } +// } + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + System.out.println(String.format("%s, ip: %s, websocket 断开连接", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), clientIp)); + + if (connectMap.get(clientIp) != null) { + connectMap.remove(clientIp); + } + } + + @Override + public void onMessage(WebSocket conn, String message) { + +// broadcast(message); + + try { + if (message.contains("longitude") && message.contains("latitude") + && message.contains("leftaddr") && message.contains("rightaddr")) { + System.out.println("切换项目: " + message); + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + LineInfo lineInfo = JSONObject.parseObject(message, LineInfo.class); + Integer projectId = Integer.valueOf(lineInfo.getId()); + ResultSet resultSet = SQLHelper.ExecProcwCommands("SELECT * FROM line WHERE id = " + projectId); + ChangeTunnelProjectRep changeTunnelProjectRep = new ChangeTunnelProjectRep(); + changeTunnelProjectRep.setCommand("changetunnelproject"); + changeTunnelProjectRep.setProjectid(projectId); + if (resultSet != null && resultSet.next()) { + changeTunnelProjectRep.setSuccessed(true); + changeTunnelProjectRep.setMessage("切换隧道成功"); + + SocketBean socketBean = new SocketBean(); + socketBean.setConn(conn); + socketBean.setProjectId(projectId); + connectMap.put(clientIp, socketBean); + + connectWaitMap.put(clientIp, 0); + } else { + changeTunnelProjectRep.setSuccessed(false); + changeTunnelProjectRep.setMessage("项目不存在"); + } + System.out.println("切换项目: " + message); + conn.send(JSON.toJSONString(changeTunnelProjectRep)); + } else if (message.contains("heartbeatmessage")) { + System.out.println("ping message: " + message); + + String clientIp = conn.getRemoteSocketAddress().getAddress().getHostAddress(); + connectWaitMap.put(clientIp, 0); + + Map map = new HashMap(); + map.put("command", "heartbeatmessage"); + map.put("successed", true); + + System.out.println(String.format("%s, ip:%s, pong message: %s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")), clientIp, JSON.toJSONString(map))); + conn.send(JSON.toJSONString(map)); + } else { + conn.send(message); + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + if (conn != null) { + // some errors like port binding failed may not be assignable to a specific + // websocket + } + + } + + public static void sendMessage(String message) { + for (Map.Entry entry : map.entrySet()) { + String ip = entry.getKey(); + try { + WebSocket conn = entry.getValue(); + + if (connectMap.get(ip) != null) { + SocketBean socketBean = connectMap.get(ip); + int projectId = socketBean.getProjectId(); + + CarCheckInfo carCheckInfo = JSONObject.parseObject(message, CarCheckInfo.class); + int line = carCheckInfo.getSensor().getLine(); + + if (projectId == line && conn != null) { + conn.send(message); +// LOGGER.info("给客户端:{},发送消息:{}", ip, message); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + LOGGER.info("WebSocket发送报文到前端发生异常,前端IP:{},错误信息:{}", ip, e.getMessage()); + } + + } + } + + @Override + public void onStart() { + System.out.println("Server started!"); + setConnectionLostTimeout(0); + setConnectionLostTimeout(100); + + Timer timer = new Timer(); + timer.schedule(new TimerTask() { + public void run() { + + System.out.println("connectWaitMap: " + JSON.toJSONString(connectWaitMap)); + for (Map.Entry entry : connectMap.entrySet()) { + String ip = entry.getKey(); + if (connectWaitMap.get(ip) != null) { + int waitCount = connectWaitMap.get(ip) + 1; + connectWaitMap.put(ip, waitCount); + + if (waitCount > 3) { +// WebsocketConnectInstance websocketConnectInstance = WebsocketConnectInstance.getInstance(); +// websocketConnectInstance.setRestart(true); + + if (connectMap.get(ip) != null) { + SocketBean socketBean = connectMap.get(ip); + WebSocket webSocket = socketBean.getConn(); + webSocket.close(); + } + } + } + } + } + }, 0, 1 * 60 * 1000); + } + + class SocketBean { + WebSocket conn; + int projectId; + public WebSocket getConn() { + return conn; + } + public void setConn(WebSocket conn) { + this.conn = conn; + } + public int getProjectId() { + return projectId; + } + public void setProjectId(int projectId) { + this.projectId = projectId; + } + } + + class ChangeTunnelProjectRep { + private String command; + private boolean successed; + private Integer projectid; + private String message; + public String getCommand() { + return command; + } + public void setCommand(String command) { + this.command = command; + } + public boolean isSuccessed() { + return successed; + } + public void setSuccessed(boolean successed) { + this.successed = successed; + } + public Integer getProjectid() { + return projectid; + } + public void setProjectid(Integer projectid) { + this.projectid = projectid; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + } + +} \ No newline at end of file diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/BaseInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/BaseInfo.java new file mode 100644 index 0000000..e4994f8 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/BaseInfo.java @@ -0,0 +1,27 @@ +package com.back.webSocket.bean; + +public class BaseInfo { + + private Integer laneCount; + private int trafficOutputFlag; + private int generalTrafficIndication; + public Integer getLaneCount() { + return laneCount; + } + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + public int getTrafficOutputFlag() { + return trafficOutputFlag; + } + public void setTrafficOutputFlag(int trafficOutputFlag) { + this.trafficOutputFlag = trafficOutputFlag; + } + public int getGeneralTrafficIndication() { + return generalTrafficIndication; + } + public void setGeneralTrafficIndication(int generalTrafficIndication) { + this.generalTrafficIndication = generalTrafficIndication; + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/CarCheckInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/CarCheckInfo.java new file mode 100644 index 0000000..210f3dc --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/CarCheckInfo.java @@ -0,0 +1,49 @@ +package com.back.webSocket.bean; + + +public class CarCheckInfo { + private String command; + private BaseInfo baseInfo; + private TargetInfo targetInfo; + public SensorInfo sensor; + private LoadInfo loadInfo; + public FlowInfo flowInfo; + + public String getCommand() { + return command; + } + public void setCommand(String command) { + this.command = command; + } + public TargetInfo getTargetInfo() { + return targetInfo; + } + public void setTargetInfo(TargetInfo targetInfo) { + this.targetInfo = targetInfo; + } + public SensorInfo getSensor() { + return sensor; + } + public void setSensor(SensorInfo sensor) { + this.sensor = sensor; + } + public LoadInfo getLoadInfo() { + return loadInfo; + } + public void setLoadInfo(LoadInfo loadInfo) { + this.loadInfo = loadInfo; + } + public FlowInfo getFlowInfo() { + return flowInfo; + } + public void setFlowInfo(FlowInfo flowInfo) { + this.flowInfo = flowInfo; + } + public BaseInfo getBaseInfo() { + return baseInfo; + } + public void setBaseInfo(BaseInfo baseInfo) { + this.baseInfo = baseInfo; + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/CarSensor.java b/carCheckNew/src/main/java/com/back/webSocket/bean/CarSensor.java new file mode 100644 index 0000000..4e2565a --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/CarSensor.java @@ -0,0 +1,106 @@ +package com.back.webSocket.bean; + +public class CarSensor extends SensorInfo { + + private int id; + private String name; + private String terminal; + private String ip; + private String port; + private int connectflag; + + public int laneweight1; + public int laneweight2; + public int laneweight3; + public int laneweight4; + public int laneweight5; + public int laneweight6; + public int laneweight7; + public int laneweight8; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public String getIp() { + return ip; + } + public void setIp(String ip) { + this.ip = ip; + } + public String getPort() { + return port; + } + public void setPort(String port) { + this.port = port; + } + public int getConnectflag() { + return connectflag; + } + public void setConnectflag(int connectflag) { + this.connectflag = connectflag; + } + public int getLaneweight1() { + return laneweight1; + } + public void setLaneweight1(int laneweight1) { + this.laneweight1 = laneweight1; + } + public int getLaneweight2() { + return laneweight2; + } + public void setLaneweight2(int laneweight2) { + this.laneweight2 = laneweight2; + } + public int getLaneweight3() { + return laneweight3; + } + public void setLaneweight3(int laneweight3) { + this.laneweight3 = laneweight3; + } + public int getLaneweight4() { + return laneweight4; + } + public void setLaneweight4(int laneweight4) { + this.laneweight4 = laneweight4; + } + public int getLaneweight5() { + return laneweight5; + } + public void setLaneweight5(int laneweight5) { + this.laneweight5 = laneweight5; + } + public int getLaneweight6() { + return laneweight6; + } + public void setLaneweight6(int laneweight6) { + this.laneweight6 = laneweight6; + } + public int getLaneweight7() { + return laneweight7; + } + public void setLaneweight7(int laneweight7) { + this.laneweight7 = laneweight7; + } + public int getLaneweight8() { + return laneweight8; + } + public void setLaneweight8(int laneweight8) { + this.laneweight8 = laneweight8; + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/FlowInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/FlowInfo.java new file mode 100644 index 0000000..046a6ad --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/FlowInfo.java @@ -0,0 +1,156 @@ +package com.back.webSocket.bean; + +import java.math.BigDecimal; +import java.util.List; + +public class FlowInfo { + + private Integer valid; + private Integer laneCount; + private List flowList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public Integer getLaneCount() { + return laneCount; + } + + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + + public List getFlowList() { + return flowList; + } + + public void setFlowList(List flowList) { + this.flowList = flowList; + } + + public static class Flow { +// private String name; +// private String comid; + private String terminal; + private int laneNumber; +// private int laneCongestion; + private BigDecimal maxCarLanesflow; + private BigDecimal maxCarAverageLanesflow; + private BigDecimal mediumCarLanesflow; + private BigDecimal mediumCarAverageLanesflow; + private BigDecimal minCarLanesflow; + private BigDecimal minCarAverageLanesflow; + private BigDecimal locomotiveLanesflow; + private BigDecimal locomotiveAverageLanesflow; + private BigDecimal motorVehicleAverageLanesflow; + private BigDecimal laneOccupancy; + private BigDecimal timeOccupancy; + private BigDecimal averageTravelTime; + private BigDecimal averageTravelDistance; + + + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } +// public int getLaneCongestion() { +// return laneCongestion; +// } +// public void setLaneCongestion(int laneCongestion) { +// this.laneCongestion = laneCongestion; +// } + public BigDecimal getMaxCarLanesflow() { + return maxCarLanesflow; + } + public void setMaxCarLanesflow(BigDecimal maxCarLanesflow) { + this.maxCarLanesflow = maxCarLanesflow; + } + public BigDecimal getMaxCarAverageLanesflow() { + return maxCarAverageLanesflow; + } + public void setMaxCarAverageLanesflow(BigDecimal maxCarAverageLanesflow) { + this.maxCarAverageLanesflow = maxCarAverageLanesflow; + } + public BigDecimal getMediumCarLanesflow() { + return mediumCarLanesflow; + } + public void setMediumCarLanesflow(BigDecimal mediumCarLanesflow) { + this.mediumCarLanesflow = mediumCarLanesflow; + } + public BigDecimal getMediumCarAverageLanesflow() { + return mediumCarAverageLanesflow; + } + public void setMediumCarAverageLanesflow(BigDecimal mediumCarAverageLanesflow) { + this.mediumCarAverageLanesflow = mediumCarAverageLanesflow; + } + public BigDecimal getMinCarLanesflow() { + return minCarLanesflow; + } + public void setMinCarLanesflow(BigDecimal minCarLanesflow) { + this.minCarLanesflow = minCarLanesflow; + } + public BigDecimal getMinCarAverageLanesflow() { + return minCarAverageLanesflow; + } + public void setMinCarAverageLanesflow(BigDecimal minCarAverageLanesflow) { + this.minCarAverageLanesflow = minCarAverageLanesflow; + } + public BigDecimal getLocomotiveLanesflow() { + return locomotiveLanesflow; + } + public void setLocomotiveLanesflow(BigDecimal locomotiveLanesflow) { + this.locomotiveLanesflow = locomotiveLanesflow; + } + public BigDecimal getLocomotiveAverageLanesflow() { + return locomotiveAverageLanesflow; + } + public void setLocomotiveAverageLanesflow(BigDecimal locomotiveAverageLanesflow) { + this.locomotiveAverageLanesflow = locomotiveAverageLanesflow; + } + public BigDecimal getMotorVehicleAverageLanesflow() { + return motorVehicleAverageLanesflow; + } + public void setMotorVehicleAverageLanesflow(BigDecimal motorVehicleAverageLanesflow) { + this.motorVehicleAverageLanesflow = motorVehicleAverageLanesflow; + } + public BigDecimal getLaneOccupancy() { + return laneOccupancy; + } + public void setLaneOccupancy(BigDecimal laneOccupancy) { + this.laneOccupancy = laneOccupancy; + } + public BigDecimal getTimeOccupancy() { + return timeOccupancy; + } + public void setTimeOccupancy(BigDecimal timeOccupancy) { + this.timeOccupancy = timeOccupancy; + } + public BigDecimal getAverageTravelTime() { + return averageTravelTime; + } + public void setAverageTravelTime(BigDecimal averageTravelTime) { + this.averageTravelTime = averageTravelTime; + } + public BigDecimal getAverageTravelDistance() { + return averageTravelDistance; + } + public void setAverageTravelDistance(BigDecimal averageTravelDistance) { + this.averageTravelDistance = averageTravelDistance; + } + + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/LineInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/LineInfo.java new file mode 100644 index 0000000..0fa43a2 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/LineInfo.java @@ -0,0 +1,81 @@ +package com.back.webSocket.bean; + +public class LineInfo { + private String id; + private String name; + private String longitude; + private String latitude; + private String leftaddr; + private String rightaddr; + private String createtime; + private String username; + private String city; + private String remark; + private String createuser; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getLongitude() { + return longitude; + } + public void setLongitude(String longitude) { + this.longitude = longitude; + } + public String getLatitude() { + return latitude; + } + public void setLatitude(String latitude) { + this.latitude = latitude; + } + public String getLeftaddr() { + return leftaddr; + } + public void setLeftaddr(String leftaddr) { + this.leftaddr = leftaddr; + } + public String getRightaddr() { + return rightaddr; + } + public void setRightaddr(String rightaddr) { + this.rightaddr = rightaddr; + } + public String getCreatetime() { + return createtime; + } + public void setCreatetime(String createtime) { + this.createtime = createtime; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getCity() { + return city; + } + public void setCity(String city) { + this.city = city; + } + public String getRemark() { + return remark; + } + public void setRemark(String remark) { + this.remark = remark; + } + public String getCreateuser() { + return createuser; + } + public void setCreateuser(String createuser) { + this.createuser = createuser; + } +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/LoadInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/LoadInfo.java new file mode 100644 index 0000000..5baa792 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/LoadInfo.java @@ -0,0 +1,53 @@ +package com.back.webSocket.bean; + +import java.util.List; + +public class LoadInfo { + + private Integer valid; + private Integer laneCount; + private List loadList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public Integer getLaneCount() { + return laneCount; + } + + public void setLaneCount(Integer laneCount) { + this.laneCount = laneCount; + } + + public List getLoadList() { + return loadList; + } + + public void setLoadList(List loadList) { + this.loadList = loadList; + } + + public static class Load { + private int laneNumber; + private int laneCongestion; + + public int getLaneNumber() { + return laneNumber; + } + public void setLaneNumber(int laneNumber) { + this.laneNumber = laneNumber; + } + public int getLaneCongestion() { + return laneCongestion; + } + public void setLaneCongestion(int laneCongestion) { + this.laneCongestion = laneCongestion; + } + } + +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/SensorInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/SensorInfo.java new file mode 100644 index 0000000..afc11b4 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/SensorInfo.java @@ -0,0 +1,125 @@ +package com.back.webSocket.bean; + +import java.util.List; + +public class SensorInfo { + private String comid; + public int lane; + public String laneflag; + public String laneMark; +// public int laneweight1; +// public int laneweight2; +// public int laneweight3; +// public int laneweight4; +// public int laneweight5; +// public int laneweight6; +// public int laneweight7; +// public int laneweight8; + public int lanelength; + public int line; + + public List laneList; + + public static class LaneWeight { + private float laneweight; + + public float getLaneweight() { + return laneweight; + } + + public void setLaneweight(float laneweight) { + this.laneweight = laneweight; + } + } + + public String getComid() { + return comid; + } + public void setComid(String comid) { + this.comid = comid; + } + public int getLane() { + return lane; + } + public void setLane(int lane) { + this.lane = lane; + } + public String getLaneflag() { + return laneflag; + } + public void setLaneflag(String laneflag) { + this.laneflag = laneflag; + } +// public int getLaneweight1() { +// return laneweight1; +// } +// public void setLaneweight1(int laneweight1) { +// this.laneweight1 = laneweight1; +// } +// public int getLaneweight2() { +// return laneweight2; +// } +// public void setLaneweight2(int laneweight2) { +// this.laneweight2 = laneweight2; +// } +// public int getLaneweight3() { +// return laneweight3; +// } +// public void setLaneweight3(int laneweight3) { +// this.laneweight3 = laneweight3; +// } +// public int getLaneweight4() { +// return laneweight4; +// } +// public void setLaneweight4(int laneweight4) { +// this.laneweight4 = laneweight4; +// } +// public int getLaneweight5() { +// return laneweight5; +// } +// public void setLaneweight5(int laneweight5) { +// this.laneweight5 = laneweight5; +// } +// public int getLaneweight6() { +// return laneweight6; +// } +// public void setLaneweight6(int laneweight6) { +// this.laneweight6 = laneweight6; +// } +// public int getLaneweight7() { +// return laneweight7; +// } +// public void setLaneweight7(int laneweight7) { +// this.laneweight7 = laneweight7; +// } +// public int getLaneweight8() { +// return laneweight8; +// } +// public void setLaneweight8(int laneweight8) { +// this.laneweight8 = laneweight8; +// } + public int getLanelength() { + return lanelength; + } + public void setLanelength(int lanelength) { + this.lanelength = lanelength; + } + public int getLine() { + return line; + } + public void setLine(int line) { + this.line = line; + } + public String getLaneMark() { + return laneMark; + } + public void setLaneMark(String laneMark) { + this.laneMark = laneMark; + } + public List getLaneList() { + return laneList; + } + public void setLaneList(List laneList) { + this.laneList = laneList; + } +} diff --git a/carCheckNew/src/main/java/com/back/webSocket/bean/TargetInfo.java b/carCheckNew/src/main/java/com/back/webSocket/bean/TargetInfo.java new file mode 100644 index 0000000..d876432 --- /dev/null +++ b/carCheckNew/src/main/java/com/back/webSocket/bean/TargetInfo.java @@ -0,0 +1,89 @@ +package com.back.webSocket.bean; + +import java.math.BigDecimal; +import java.util.List; + +public class TargetInfo { + + private Integer valid; + private int targetCount; + private List targetList; + + public Integer getValid() { + return valid; + } + + public void setValid(Integer valid) { + this.valid = valid; + } + + public int getTargetCount() { + return targetCount; + } + + public void setTargetCount(int targetCount) { + this.targetCount = targetCount; + } + + public List getTargetList() { + return targetList; + } + + public void setTargetList(List targetList) { + this.targetList = targetList; + } + + public static class Target { + private int targetNum; + private int targetType; + private int laneNum; + private BigDecimal xDistance; + private BigDecimal yDistance; + private BigDecimal xFlow; + private BigDecimal yFlow; + + public BigDecimal getxDistance() { + return xDistance; + } + public void setxDistance(BigDecimal xDistance) { + this.xDistance = xDistance; + } + public BigDecimal getyDistance() { + return yDistance; + } + public void setyDistance(BigDecimal yDistance) { + this.yDistance = yDistance; + } + public BigDecimal getxFlow() { + return xFlow; + } + public void setxFlow(BigDecimal xFlow) { + this.xFlow = xFlow; + } + public BigDecimal getyFlow() { + return yFlow; + } + public void setyFlow(BigDecimal yFlow) { + this.yFlow = yFlow; + } + public int getTargetNum() { + return targetNum; + } + public void setTargetNum(int targetNum) { + this.targetNum = targetNum; + } + public int getTargetType() { + return targetType; + } + public void setTargetType(int targetType) { + this.targetType = targetType; + } + public int getLaneNum() { + return laneNum; + } + public void setLaneNum(int laneNum) { + this.laneNum = laneNum; + } + } + +} diff --git a/carCheckNew/target/classes/META-INF/MANIFEST.MF b/carCheckNew/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..bd2d96f --- /dev/null +++ b/carCheckNew/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: Administrator +Build-Jdk: 1.8.0_351 +Created-By: Maven Integration for Eclipse + diff --git a/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.properties b/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.properties new file mode 100644 index 0000000..94f7361 --- /dev/null +++ b/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Jun 05 23:14:39 CST 2024 +version=0.0.1-SNAPSHOT +groupId=com.back +m2e.projectName=2-carCheckNew +m2e.projectLocation=D\:\\fyj_20240312\\processor\\carCheckNew +artifactId=carCheckNew diff --git a/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.xml b/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.xml new file mode 100644 index 0000000..754b41c --- /dev/null +++ b/carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + carCheckNew + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 0000000..3ef61a2 --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + common + jar + + + + + org.apache.commons + commons-lang3 + 3.8 + + + + com.alibaba + fastjson + 1.2.66 + + + + mysql + mysql-connector-java + 5.1.40 + + + + org.slf4j + slf4j-api + 1.7.25 + + + + + org.apache.httpcomponents + httpclient + 4.5.6 + + + + com.google.code.gson + gson + 2.8.9 + + + + + org.bidib.jbidib.org.qbang.rxtx + rxtxcomm + 2.2 + + + + org.scream3r + jssc + 2.8.0 + + + + com.sun.mail + javax.mail + 1.6.2 + + + + + + + org.eclipse.milo + sdk-client + 0.6.3 + + + + org.java-websocket + Java-WebSocket + 1.5.3 + + + + \ No newline at end of file diff --git a/common/src/main/java/com/back/action/Log.java b/common/src/main/java/com/back/action/Log.java new file mode 100644 index 0000000..ce6cb4e --- /dev/null +++ b/common/src/main/java/com/back/action/Log.java @@ -0,0 +1,167 @@ +package com.back.action; + +import com.back.common.Common; + +import java.io.File; +import java.io.FileWriter; +import java.util.Calendar; +import java.util.Random; + +public class Log { + + static int count = 0; + static long size = 0; + static String text = "";// 要写入的文本 + static String filename = "";// 文件名 + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public synchronized static void writelog1(String msg) { + System.err.println(Common.getDateStr0() + ":" + msg); + + File f = null; + try { + count = count + 1; + text = text + Common.getDateStr0() + ":" + msg + "\r\n"; + + // 十行写一次 + if (count == 10) { + f = new File(".\\Log"); + if (!f.exists()) { + f.mkdir();// 创建文件夹 + } + + if (filename.equals("")) { + filename = ".\\Log\\" + Common.getDateStr1() + getRandom(5) + ".log"; + } + f = new File(filename); + if (!f.exists()) { + f.createNewFile();// 不存在则创建 + f = new File(filename);// 重新实例化 + } else { + size = f.length(); + if (size >= 1024000) {// 创建新文件 + filename = ".\\Log\\" + Common.getDateStr1() + getRandom(5) + ".log"; + f = new File(filename); + if (!f.exists()) { + f.createNewFile();// 不存在则创建 + f = new File(filename);// 重新实例化 + } + } + } + + FileWriter fw = new FileWriter(f, true); + fw.write(text); + fw.flush(); + fw.close(); + fw = null; + count = 0; + text = ""; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public synchronized static void writelog(String classObject, String msg) { + System.err.println(Common.getDateStr0() + "[" + classObject + "]:" + msg); + + File f = null; + try { + count = count + 1; + text = text + Common.getDateStr0() + ":[" + classObject + "]" + msg + "\r\n"; + + // 十行写一次 + if (count == 300) { + f = new File(".\\Log"); + if (!f.exists()) { + f.mkdir();// 创建文件夹 + } + + if (filename.equals("")) { + filename = ".\\Log\\" + Common.getDateStr1() + getRandom(5) + ".log"; + } + f = new File(filename); + if (!f.exists()) { + f.createNewFile();// 不存在则创建 + f = new File(filename);// 重新实例化 + } else { + size = f.length(); + if (size >= 1024000) {// 创建新文件 + filename = ".\\Log\\" + Common.getDateStr1() + getRandom(5) + ".log"; + f = new File(filename); + if (!f.exists()) { + f.createNewFile();// 不存在则创建 + f = new File(filename);// 重新实例化 + } + } + } + + FileWriter fw = new FileWriter(f, true); + fw.write(text); + fw.flush(); + fw.close(); + fw = null; + count = 0; + text = ""; + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * 返回一个随机数 + * + * @param i + * 随机数长度 + */ + public static String getRandom(int i) { + Random rd = new Random(); + if (i == 0) + return ""; + String result = ""; + for (int k = 0; k < i; k++) { + result = result + rd.nextInt(9); + } + return result; + } + + /** 删除一个月之前的日志文件 */ + public static boolean deleteFile() { + File file = new File(".\\Log"); + String[] filelist = file.list(); + try { + for (int i = 0; i < filelist.length; i++) { + File delfile = new File(".\\Log\\" + filelist[i]); + if (!delfile.isDirectory()) { + + int year = Integer.parseInt(delfile.getName().substring(0, 4)); + int month = Integer.parseInt(delfile.getName().substring(4, 6)) - 1; + int day = Integer.parseInt(delfile.getName().substring(6, 8)); + + Calendar calendar1 = Calendar.getInstance(); + calendar1.set(year, month, day); + + Calendar calendar0 = Calendar.getInstance(); + calendar0.add(Calendar.MONTH, -1); + + if (calendar1.before(calendar0)) { + if (delfile.delete()) { + writelog(Log.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->LogFile:" + delfile.getName()); + } + } + } + } + return true; + } catch (Exception e) { + return false; + } + } +} \ No newline at end of file diff --git a/common/src/main/java/com/back/common/Common.java b/common/src/main/java/com/back/common/Common.java new file mode 100644 index 0000000..2af5d97 --- /dev/null +++ b/common/src/main/java/com/back/common/Common.java @@ -0,0 +1,689 @@ +package com.back.common; + +import java.io.UnsupportedEncodingException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 通用函数类 + */ +public class Common { + + /** + * Ascii码字符串转成16进制字符串 主要用于Lon16的码命令,从 + * + * @param msg + * @return + */ + public static String Ascii2Hex(String msg) { + String resultString = ""; + for (int i = 0; i < msg.length(); i++) { + int num = msg.charAt(i); + String temp = Integer.toHexString(num).toUpperCase(); + if (temp.length() == 1) + resultString = resultString + "0" + temp; + else + resultString = resultString + temp; + } + + return resultString; + } + + /** + * @功能: BCD码转为10进制串(阿拉伯数据) + * @参数: BCD码 + * @结果: 10进制串 + */ + public static String bcd2Str(byte[] bytes) { + StringBuffer temp = new StringBuffer(bytes.length * 2); + for (int i = 0; i < bytes.length; i++) { + temp.append(dec2Hex(((bytes[i] & 0xf0) >> 4), 1)); + temp.append(dec2Hex(((bytes[i] & 0x0f)), 1)); + } + return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) + : temp.toString(); + } + + /** + * @功能: 10进制串转为BCD码 + * @参数: 10进制串 + * @结果: BCD码 + */ + public static byte[] str2Bcd(String asc) { + int len = asc.length(); + int mod = len % 2; + if (mod != 0) { + asc = "0" + asc; + len = asc.length(); + } + byte abt[] = new byte[len]; + if (len >= 2) { + len = len / 2; + } + byte bbt[] = new byte[len]; + abt = asc.getBytes(); + int j, k; + for (int p = 0; p < asc.length() / 2; p++) { + if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) { + j = abt[2 * p] - '0'; + } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) { + j = abt[2 * p] - 'a' + 0x0a; + } else { + j = abt[2 * p] - 'A' + 0x0a; + } + if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) { + k = abt[2 * p + 1] - '0'; + } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) { + k = abt[2 * p + 1] - 'a' + 0x0a; + } else { + k = abt[2 * p + 1] - 'A' + 0x0a; + } + int a = (j << 4) + k; + byte b = (byte) a; + bbt[p] = b; + } + return bbt; + } + + /** 正则表达式判断是否为数字 */ + public static boolean isNumeric(String str) { + Pattern pattern = Pattern.compile("[0-9]*"); + Matcher isNum = pattern.matcher(str); + if (!isNum.matches()) { + return false; + } + return true; + } + + /** 16进制转10进制 */ + public static int hextoint(String hex) { + int result = Integer.parseInt(hex, 16); + return result; + } + + /** + * 10进制转16进制 + * + * @param integer + * @return + */ + public static String inttohex(int integer) { + String result = Integer.toHexString(integer).toUpperCase(); + return result; + } + + /** 16进制转2进制 */ + public static String hextobinary(String hex) { + int temp = Integer.parseInt(hex, 16); + String binary = Integer.toBinaryString(temp); + binary = right(binary, 8); + return binary; + } + + /** 2进制转16进制 */ + public static String binarytohex(String binary) { + int temp = binarytoint(binary); + return Integer.toHexString(temp); + } + + /** 2进制转10进制 */ + public static int binarytoint(String binary) { + return Integer.valueOf(binary, 2); + } + + /***/ + public static String inttobinary(int integer) { + return Integer.toBinaryString(integer); + } + + /** 从右边取指定长度字符 */ + public static String right(String input, int count) { + count = (count > input.length()) ? input.length() : count; + return input.substring(input.length() - count, input.length()); + } + + /** 从左边取指定长度字符 */ + public static String left(String input, int count) { + count = (count > input.length()) ? input.length() : count; + return input.substring(0, count); + } + + /** 字节数组转换成16进制字符串 */ + public static String GetHexStr(byte[] bytes, int num) { + String temp = ""; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < num; i++) { + temp = (Integer.toHexString(bytes[i] & 0XFF)); + if (temp.length() == 1) { + temp = "0" + temp; + } + sb.append(temp + "-"); + } + return sb.toString().toUpperCase(); + } + + /** 字节数组转换成字符串 */ + public static String GetAsciiStr(byte[] bytes, int num) { + char c; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < num; i++) { + c = (char) bytes[i]; + sb.append(c); + } + return sb.toString(); + } + + /** + * 添加小数点 + * + * @param input + * @param intNum + * 整数位数 + * @return + */ + public static String AddDecimalPoint(String input, int intNum) { + return input.substring(0, intNum) + "." + input.substring(intNum); + } + + /** + * 16进制字符串转成Asc码字符串 + * + * @param input + * @return + */ + public static String HexStr2AsciiStr(String input) { + char c; + StringBuilder sb = new StringBuilder(); + int num = input.length() / 2; + for (int i = 0; i < num; i++) { + String str = input.substring(2 * i, (i + 1) * 2); + c = (char) hextoint(str); + sb.append(c); + } + return sb.toString(); + } + + /** + * 10进制转16进制 + * + * @param dec + * 要转换的数值 + * @param len + * 16进制的长度 + * @return + */ + public static String dec2Hex(int dec, int len) { + String tempString = Integer.toHexString(dec).toUpperCase(); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + + /** + * 10进制转16进制 + * + * @param dec + * 要转换的数值 + * @param len + * 16进制的长度 + * @return + */ + public static String dec2Hex(Long dec, int len) { + String tempString = Long.toHexString(dec).toUpperCase(); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + + /** byte转换成十六进制字符串 */ + public static String bytetohex(byte b) { + String stmp = (Integer.toHexString(b & 0XFF)); + System.out.println(stmp); + if (stmp.length() == 1) + stmp = "0" + stmp; + return stmp.toUpperCase(); + } + + /** 按长度2分割字符串,以"-"连接 */ + public static String str2split(String str) { + char[] array = str.toCharArray(); + str = ""; + for (int i = 0; i < array.length / 2; i++) { + str += String.valueOf(array[i * 2]) + String.valueOf(array[i * 2 + 1]) + "-"; + } + return str; + } + + /** 发短信息:奇偶位互换 */ + public static String ParityChange(String msg) { + StringBuffer buf = new StringBuffer(); + char[] chars = msg.toCharArray(); + for (int i = 1; i < chars.length; i += 2) { + buf.append(chars[i]); + buf.append(chars[i - 1]); + } + return buf.toString(); + } + + /** + * PDU格式短消息中心号码编码 + * + * @param center + * 短消息中心号码 + * @return PDU短信中心格式编码 + */ + public static String PDUCenter(String center) { + int intLen = center.length(); + if (intLen % 2 == 1) {// 为奇数则加F + center += "F"; + intLen++; + } + center = ParityChange(center); // 奇数位和偶数位交换 + center = "91" + center;// 短信中心号码前加91 + intLen = center.length() / 2;// 短信中心号码长度除2,结果格式化成2位的16进制字符串 + String strLen = right("00" + inttohex(intLen), 2); + center = strLen + center; + + return center; + } + + /** + * PDU格式接收手机号码加信息内容编码 + * + * @param phone + * 接收手机号码 + * @param msg + * 短信内容 + * @return PDU格式短信编码 + */ + public static String PDUCode(String phone, String msg) { + + int intLen = phone.length(); + if (intLen % 2 == 1) {// 为奇数则加F + phone += "F"; + intLen++; + } + phone = ParityChange(phone); // 奇数位和偶数位交换 + + String code = ""; + byte[] bytes = null; + try { + bytes = msg.getBytes("UTF-16"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + for (int i = 2; i < bytes.length; i++) { + code += byte2Hex(bytes[i]); + } + + intLen = code.length() / 2; + String strLen = right("00" + inttohex(intLen), 2); + code = strLen + code; + + phone = "11000D91" + phone;// 前面加11000D91 + code = phone + "000800" + code; + return code; + } + + /** + * 在字符串左边添加字符串 + * + * @param sourceStr + * 源字符串 + * @param lenStr + * 目标字符串的长度 + * @param filler + * 要填充的字符串 + * @return + */ + public static String lPad(String sourceStr, int lenStr, String filler) { + sourceStr = sourceStr.trim(); + int m = sourceStr.length(); + m = lenStr - m; + if (m < 1) { + return sourceStr; + } + + if ((m % (filler.length())) == 0) { + m = m / (filler.length()); + } else { + m = m / (filler.length()); + m++; + } + + for (int i = 0; i < m; i++) { + sourceStr = filler + sourceStr; + } + + return sourceStr; + } + + /** + * byte转u25442 为u21313 六u-28709 制 + * + * @param b + * byte + * @return String + */ + public static String byte2Hex(byte b) { + return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF".charAt(b & 0xf)); + } + + /** 获取当前时间 */ + public static Date getcurdate() { + Date curdate = new Date(); + return curdate; + } + /** + * 获取时区 + * @return + */ + public static TimeZone getTimeZone() + { + //指定东8区 + //return TimeZone.getTimeZone("GMT+8"); + + //获取系统当前默认时区 + return TimeZone.getDefault(); + } + /** 返回时间字符串:yyyy */ + public static String getYear() { + SimpleDateFormat format = new SimpleDateFormat("yyyy"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:mm */ + public static String getMinute() { + SimpleDateFormat format = new SimpleDateFormat("mm"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:mm */ + public static String getMinute(Date currDate) { + SimpleDateFormat format = new SimpleDateFormat("mm"); + format.setTimeZone(getTimeZone()); + return format.format(currDate); + } + + /** 返回时间字符串:yyyy-MM-dd HH:mm:ss */ + public static String getDateStr0() { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回当前时间字符串:yyyy-MM-dd HH:mm:ss */ + + public static String getYesterdayStr0() { + String datestr; + Date currDate = new Date(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(currDate); + calendar.add(calendar.DATE, -1); + currDate = calendar.getTime(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + format.setTimeZone(getTimeZone()); + // Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:yyyyMMddHHmmssSSS */ + public static String getDateStr1() { + String datestr; + Date currDate = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS"); + format.setTimeZone(getTimeZone()); + datestr = format.format(currDate); + return datestr; + } + + /** 返回时间字符串:yyyy-MM-dd HH:mm:ss SSS */ + public static String getDateStr2() { + String datestr; + Date currDate = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); + format.setTimeZone(getTimeZone()); + datestr = format.format(currDate); + return datestr; + } + + /** 返回时间字符串:yyyy-MM-dd-HH-mm-ss */ + public static String getDateStr3() { + String datestr; + Date currDate = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); + format.setTimeZone(getTimeZone()); + datestr = format.format(currDate); + return datestr; + } + + /** 返回时间字符串:HH:mm */ + public static String getDateStr4() { + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:ddMMyy */ + public static String getDateStr5() { + SimpleDateFormat format = new SimpleDateFormat("ddMMyy"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:mmHHddMMyy,分时日月年(Td_c) */ + public static String getDateStr6() { + SimpleDateFormat format = new SimpleDateFormat("mmHHddMMyy"); + format.setTimeZone(getTimeZone()); + Date currDate = new Date(); + return format.format(currDate); + } + + /** 返回时间字符串:yyyy-MM-dd */ + public static String getDateStr7() { + String datestr; + Date currDate = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setTimeZone(getTimeZone()); + datestr = format.format(currDate); + return datestr; + } + + /** + * 返回昨天时间字符串 + * + * @return返回昨天时间字符串:yyyy-MM-dd + */ + public static String getYesterdayStr7() { + String datestr; + Date currDate = new Date(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(currDate); + calendar.add(calendar.DATE, -1); + currDate = calendar.getTime(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + format.setTimeZone(getTimeZone()); + datestr = format.format(currDate); + return datestr; + } + + /** 数据内低字节在前,高字节在后 */ + public static String InterChange(String value) { + StringBuffer buf = new StringBuffer(); + char[] chars = value.toCharArray(); + for (int i = chars.length; i > 1; i -= 2) { + buf.append(chars[i - 1]); + buf.append(chars[i]); + } + return buf.toString(); + } + + /** * 格式化时间字符串(ssmmHHddMMyyyy),返回Date类型 */ + public static Date formattime0(String time) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + Date dt = new Date(); + try { + dt = format.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + } + return dt; + } + + /** * 格式化时间字符串(ssmmHHddMMyyyy),返回String类型 */ + public static String formattime1(String time) { + SimpleDateFormat format = new SimpleDateFormat("ssmmHHddMMyyyy"); + try { + Date dt = format.parse(time); + format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return format.format(dt); + } catch (ParseException e) { + e.printStackTrace(); + } + return ""; + } + + /** * 格式化时间字符串(mmHHddMMyy),返回String类型 */ + public static String formattime2(String time) { + SimpleDateFormat format = new SimpleDateFormat("mmHHddMMyy"); + try { + Date dt = format.parse(time); + format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return format.format(dt); + } catch (ParseException e) { + e.printStackTrace(); + } + return ""; + } + + /** * 格式化时间字符串(yyyy-MM-dd HH:mm:ss),返回Date类型 */ + public static Date formattime3(String time) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date dt = new Date(); + try { + dt = format.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + } + return dt; + } + + /** 时间字符串加指定时间(分钟) */ + public static String timeadd(String time, int min) { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date dt = formattime0(time); + long afterTime = (dt.getTime() / 1000) + 60 * min; + dt.setTime(afterTime * 1000); + return format.format(dt); + } + + // 解密连接配置文件 + public static String decode(String ciphertext) { + + String outstr = ""; + char chr; + int len = 0; + long x = 0, y = 0, bit = 0; + + len = ciphertext.length(); + for (int i = 0; i < len; i = i + 2) { + bit = ciphertext.charAt(i); + // 取前4位值 + y = (bit - 64) * 16; + // 取后4位值 + y = y + ciphertext.charAt(i + 1) - 64; + chr = (char) y; + outstr = outstr + String.valueOf(chr); + } + + ciphertext = outstr; + outstr = ""; + + len = ciphertext.length(); + x = ciphertext.charAt(len - 1); + for (int i = len - 2; i >= 0; i--) { + y = x * 256 + ciphertext.charAt(i); + x = y % 13; + chr = (char) (y / 13); + outstr = String.valueOf(chr) + outstr; + } + return outstr; + } + + // 抄读电能表日冻结类数据时标Td_d(日月年) + // 2013 04 11 wwb add + public static String meterGetTd_d() { + String td_d = ""; + + SimpleDateFormat format = new SimpleDateFormat("ddMMyy"); + Calendar c = Calendar.getInstance(); + Date currDate = new Date(); + c.setTime(currDate); + int day = c.get(Calendar.DATE); + c.set(Calendar.DATE, day - 1); + td_d = format.format(c.getTime()); + + return td_d; + } + + // 抄读灯控器日冻结类数据时标Td_d(日月年) + @SuppressWarnings("deprecation") + public static String getTd_d(Date currDate) { + SimpleDateFormat format = new SimpleDateFormat("ddMMyy"); + Date date = new Date(); + + // 抄读灯控器日冻结数据时,12点之前带上日时标,12点之后带当日时标 + if (date.getHours() < 12) { + date.setDate(date.getDate()); + } + + return format.format(date); + } + + // 抄读电能表日冻结类数据时标Td_c(日月年) + // 2017 01 15 wwb add + // 15分钏 + public static String meterGetTd_c(Date currDate) { + String td_c = ""; + + SimpleDateFormat format = new SimpleDateFormat("HHddMMyy"); + + int currentmin = Integer.parseInt(Common.getMinute(currDate)); + currentmin = (currentmin / 15) * 15; + String str = String.valueOf(currentmin); + if (str.length() == 1) + str = "0" + str; + td_c = str + format.format(currDate) + "0101"; + + return td_c; + } + + // 抄读电能表日冻结类数据时标Td_c(日月年) + // 2017 01 15 wwb add + // 15分钏 + public static String meterGetTd_c1(Date currDate) { + String td_c = ""; + + SimpleDateFormat format = new SimpleDateFormat("HHddMMyy"); + + td_c = "00" + format.format(currDate) + "0104"; + + return td_c; + } +} \ No newline at end of file diff --git a/common/src/main/java/com/back/common/MeterTimingParams.java b/common/src/main/java/com/back/common/MeterTimingParams.java new file mode 100644 index 0000000..d810536 --- /dev/null +++ b/common/src/main/java/com/back/common/MeterTimingParams.java @@ -0,0 +1,50 @@ +package com.back.common; +/** + * 电表定采参数类 + * @author welcomecc + * + */ +public class MeterTimingParams { + /** + * 错误重发次数 + */ + public int reSend; + /** + * 同时并发数 + */ + public int parallel; + /** + * 巡检日志工作状态 + */ + public int logSet; + /** + * 开始时间 格式: HH:MM + */ + public String firstRunTime; + /** + * 定采间隔 或补抄间隔 + */ + public int intervalTiming; + /** + * 运行次数 或补抄次数 + */ + public int runNum; + + + /** + * 曲线抄表间隔 + */ + public int density; + + + /** + * 国网集中器一包的抄读数量 + */ + public int packsize; + + /** + * 光感控制-照度变化阀值 + */ + public Long luxChangeLimit = (long) 1000; + +} diff --git a/common/src/main/java/com/back/common/OpcDeviceParams.java b/common/src/main/java/com/back/common/OpcDeviceParams.java new file mode 100644 index 0000000..b5cc5a3 --- /dev/null +++ b/common/src/main/java/com/back/common/OpcDeviceParams.java @@ -0,0 +1,11 @@ +package com.back.common; + +public class OpcDeviceParams { + public boolean enable; + public String opcIp; + public String opcPort; + public String opcUserName; + public String opcPassword; + public int opcCycleTime; + public int opcTimeOut; +} diff --git a/common/src/main/java/com/back/common/RunParams.java b/common/src/main/java/com/back/common/RunParams.java new file mode 100644 index 0000000..14c0a0a --- /dev/null +++ b/common/src/main/java/com/back/common/RunParams.java @@ -0,0 +1,63 @@ +package com.back.common; +/** + * 前置机运行参数类 + * @author welcomecc + * + */ +public class RunParams { + public String gprsIp;// GPRS 服务器IP + public int gprsPort;// GPRS 服务器端口 + + public String gprsIpLon;// GPRS 服务器IP Lon16 + public int gprsPortLon;// GPRS 服务器端口 Lon16 + + public String websocketIp;// websocket 连接IP + public int websocketPort;// websocket 连接端口 + + public boolean carCheckSocketIsOpen;// 车检器是否开启 + public String carCheckSocketIp;// 车检器连接IP + public int carCheckSocketPort;// 车检器连接端口 + public int carCheckSocketTimeOut;// 车检器连接超时 + public int carCheckSocketSaveInteval;// 车检器上传数据时间间隔 + + public int gprsTimeOut;// GPRS超时时间(毫秒) + public int reSend;// 错误重发次数 + + public int comTimeOut;// 串口超时时间(毫秒) + public String terminalCom;// 集中器连接串口 + + public int intervalEvent;// 事件数据解析间隔时间(分) + + public int threadsize;// 线程池线程数 + public int intervalScan;// 线程池线程检视间隔时间(分) + public int timeDiscard;// 超时不处理时间(秒) + + + + public String terminalCom485;// 485总线通信口 例: COM + public int beat485;// 485集中器跳时间 (毫秒) + public int comTimeOut485;// 集中器连接串口(毫秒) + + public int devideSyncTime; // 设备数据同步周期(单位:秒) + + public String language = "";//语言 + + public Boolean opcControl= false;//光控转发处理 + + public Boolean MControlTiming15= false;//线路开关 15分钟定时抄读任务 + + public Boolean MControlTiming60= false;//线路开关 60分钟定时抄读任务 + + public Boolean LampTiming= false;//路灯曲线 抄读任务 + + public Boolean ForWard485=false;//485集中器转发命令 + + public Boolean TerminalDay3761Timing=false;//集中器日冻结 抄读任务 + + public Boolean LampDay3761Timing=false;//灯具日冻结 抄读任务 + + public Boolean AnalysisOfTunnelElectricity = false;//隧道用电分析 + + + +} diff --git a/common/src/main/java/com/back/jdbc/SQLHelper.java b/common/src/main/java/com/back/jdbc/SQLHelper.java new file mode 100644 index 0000000..46b62cc --- /dev/null +++ b/common/src/main/java/com/back/jdbc/SQLHelper.java @@ -0,0 +1,401 @@ +/** + * 获取数据连接 + */ +package com.back.jdbc; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import com.back.action.Log; + +/** SQL 基本操作 */ +public class SQLHelper { + /* + * public static String driver = + * "com.microsoft.jdbc.sqlserver.SQLServerDriver"; public static String url + * = "jdbc:microsoft:sqlserver://192.168.0.82:1433;databasename=JFGLD"; + * public static String user = "sa"; public static String pwd = ""; + */ + public static String driver; + public static String url; + public static String user; + public static String pwd; + + public static boolean isclose = false;// 数据库连接是否关闭 + + static Connection conn0 = null;// 增 + static Connection conn1 = null;// 查 + static Connection conn2 = null;// 改 + static Connection conn3 = null;// 删 + static Connection conn4 = null;// 查 + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /** + * 获取一个数据库连接 通过设置类的 driver / url / user / pwd 这四个静态变量来 设置数据库连接属性 + * + * @return 数据库连接 + */ + public static Connection getConnection() { + try { + // InputStream ins = + // ClassLoader.getSystemResourceAsStream("conn.properties"); + InputStream ins = new FileInputStream(System.getProperty("user.dir") + "\\conn.properties"); + //InputStream ins = SQLHelper.class.getClassLoader().getResourceAsStream("conn.properties"); + Properties p = new Properties(); + p.load(ins); + + driver = p.getProperty("driver"); + // driver = Common.decode(driver); + url = p.getProperty("url"); + // url = Common.decode(url); + user = p.getProperty("user"); + // user = Common.decode(user); + pwd = p.getProperty("pwd"); + // pwd = Common.decode(pwd); + } catch (IOException e) { + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + try { + Class.forName(driver); // 获取驱动 + Connection conn = DriverManager.getConnection(url, user, pwd); + isclose = false; + return conn; + } catch (Exception ex) { + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR1:" + ex.getMessage()); + isclose = true; + return null; + } + } + + /** + * 执行 SQL 语句,返回结果为整型 主要用于执行非查询语句 + * + * @param cmdText + * SQL 语句 + * @return 非负数:正常执行; -1:执行错误; -2:连接错误 synchronized + */ + public static int ExecSql(String cmdText) { + if (conn0 == null) { + conn0 = getConnection(); + } + if (conn0 == null) { + return -2; + } + Statement stmt = null; + int i; + // System.err.println(cmdText); + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->sql:" + cmdText); + try { + stmt = conn0.createStatement(); + i = stmt.executeUpdate(cmdText); // 影响的结果数 + // System.out.println("executeUpdate->>" + String.valueOf(i)); + } catch (SQLException ex) { + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + ex.getMessage()); + + isclose = true; + i = -2; + } + try { + if (stmt != null) { + stmt.close(); + stmt = null; + } + if (conn0 != null) + conn0.close(); + conn0 = null; + } catch (SQLException e) { + e.printStackTrace(); + } + return i; + } + + /** 执行存储过程proc_wCommands */ + public static synchronized ResultSet ExecProcwCommands(String cmdText) { + if (conn1 == null) { + conn1 = getConnection(); + } + if (conn1 == null) { + return null; + } + int i; +// CallableStatement c = null; + Statement stmt = null; + ResultSet rSet = null; + try { + stmt = conn1.createStatement(); + rSet = stmt.executeQuery(cmdText); + /*// 创建存储过程的对象 + c = conn1.prepareCall("{call proc_wcommands(?,?)}"); + // 给存储过程的第一个参数设置值 + c.setInt(1, cmdid); + // 注册存储过程的第二个参数 + c.registerOutParameter(2, java.sql.Types.INTEGER); + // 执行存储过程 + c.execute(); + // 得到存储过程的输出参数值 + i = c.getInt(2);*/ + } catch (SQLException ex) { + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + ex.getMessage()); + isclose = true; + try { + if (rSet != null) + rSet.close(); + if (stmt != null) + stmt.close(); + if (conn1 != null) + conn1.close(); + rSet = null; + stmt = null; + conn1 = null; + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + return rSet; + } + + /** 执行存储过程proc_wreceivedata */ + public static synchronized int ExecProcwreceivedata(int cmdid, String terminal, String tdata, int state, + String remark) { + int i; + if (conn2 == null) { + conn2 = getConnection(); + } + if (conn2 == null) { + return -2; + } + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String newDate = sdf.format(new Date()); + String data = ""; + if (tdata != null && tdata.length() > 0) { + data = tdata; + } + String sql = "INSERT INTO receivedata values (" + cmdid + "," + terminal + ",'" + data + "','" + newDate + + "',0," + state + ",'" + remark + "')"; + int result = 0; + PreparedStatement stmt = null; + try { + stmt = (PreparedStatement) conn2.prepareCall(sql); + result = stmt.executeUpdate(sql); + } catch (SQLException ex) { + Log.writelog(SQLHelper.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + + ex.getMessage() + "\r\n cmdid:" + cmdid); + isclose = true; + return -2; + } finally { + try { + if (stmt != null) { + stmt.close(); + stmt = null; + } + if (conn2 != null) { + conn2.close(); + conn2 = null; + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + /* + * CallableStatement c = null; try { // 创建存储过程的对象 c = conn2.prepareCall( + * "{call proc_wreceivedata(?,?,?,?,?,?)}"); // 给存储过程的参数设置值 c.setInt(1, + * cmdid); c.setString(2, terminal); c.setString(3, tdata); c.setInt(4, + * state); c.setString(5, remark); // 注册存储过程的第二个参数 + * c.registerOutParameter(6, java.sql.Types.INTEGER); // 执行存储过程 + * c.execute(); // 得到存储过程的输出参数值 i = c.getInt(6); } catch (SQLException + * ex) { Log.writelog(SQLHelper.clazzName, + * Thread.currentThread().getStackTrace()[1].getMethodName() + + * "->Error:" + ex.getMessage()); isclose = true; i = -2; } try { if (c + * != null) { c.close(); c = null; } } catch (SQLException e) { + * e.printStackTrace(); } + */ + return result; + } + + /** + * 保存数据到数据库 + */ + public static synchronized int saveData(String insertSql) { + int i; + if (conn2 == null) { + conn2 = getConnection(); + } + if (conn2 == null) { + return -2; + } + + int result = 0; + PreparedStatement stmt = null; + try { + stmt = (PreparedStatement) conn2.prepareCall(insertSql); + result = stmt.executeUpdate(insertSql); + } catch (SQLException ex) { +// Log.writelog(SQLHelper.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" +// + ex.getMessage() + "\r\n cmdid:" + cmdid); + isclose = true; + return -2; + } finally { + try { + if (stmt != null) { + stmt.close(); + stmt = null; + } + if (conn2 != null) { + conn2.close(); + conn2 = null; + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * 返回一个 ResultSet + * + * @param cmdText + * SQL 语句 + * @return + */ + public static synchronized ResultSet getResultSet(String cmdText) { + + if (conn3 == null) { + conn3 = getConnection(); + } + if (conn3 == null) { + return null; + } + + Statement stmt = null; + ResultSet rSet = null; + // Log.writelog(clazzName, + // Thread.currentThread().getStackTrace()[1].getMethodName() + "->" + // + cmdText); + try { +// Log.writelog(SQLHelper.clazzName, +// Thread.currentThread().getStackTrace()[1].getMethodName() + "进入" + cmdText); + stmt = conn3.createStatement(); + rSet = stmt.executeQuery(cmdText); +// Log.writelog(SQLHelper.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "退出"); + } catch (SQLException ex) { + Log.writelog(SQLHelper.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + + ex.getMessage() + "\r\n" + cmdText); + isclose = true; + try { + if (rSet != null) + rSet.close(); + if (stmt != null) + stmt.close(); + if (conn3 != null) + conn3.close(); + rSet = null; + stmt = null; + conn3 = null; + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + return rSet; + } + + /** 查询是否有记录 */ + public static boolean IsExist(String cmdText) { + boolean flag = false; + + if (conn4 == null) { + conn4 = getConnection(); + } + if (conn4 == null) { + return false; + } + Statement stmt = null; + ResultSet rSet = null; + try { + stmt = conn4.createStatement(); + rSet = stmt.executeQuery(cmdText); + } catch (SQLException ex) { + Log.writelog(SQLHelper.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + ex.getMessage()); + isclose = true; + try { + if (rSet != null) + rSet.close(); + if (stmt != null) + stmt.close(); + if (conn4 != null) + conn4.close(); + rSet = null; + stmt = null; + conn4 = null; + } catch (SQLException e) { + e.printStackTrace(); + } + return false; + } + // Log.writelog(SQLHelper.clazzName, "SQLHelper->IsExist for"); + // 判断查询回来结果 + int intcount = 0; + try { + while (rSet.next()) { + intcount = Integer.parseInt(rSet.getString(1)); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + try { + if (rSet != null) + rSet.close(); + if (stmt != null) + stmt.close(); + if (conn4 != null) + conn4.close(); + rSet = null; + stmt = null; + conn4 = null; + } catch (SQLException e) { + e.printStackTrace(); + } + conn4 = null; + } + // Log.writelog(SQLHelper.clazzName, "SQLHelper->IsExist over "); + if (intcount != 0) { + flag = true; + } + return flag; + } + + /** 清空连接 */ + public static void closeconn() { + conn0 = null; + conn1 = null; + conn2 = null; + conn3 = null; + conn4 = null; + } +} diff --git a/common/src/main/java/com/back/protocol/SystemParameter.java b/common/src/main/java/com/back/protocol/SystemParameter.java new file mode 100644 index 0000000..dbd5093 --- /dev/null +++ b/common/src/main/java/com/back/protocol/SystemParameter.java @@ -0,0 +1,518 @@ +/*系统参数查询*/ +package com.back.protocol; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Properties; + +import com.back.action.Log; +import com.back.common.MeterTimingParams; +import com.back.common.OpcDeviceParams; +import com.back.common.RunParams; +import com.back.jdbc.SQLHelper; +import com.back.*; + +public class SystemParameter { + public static RunParams runParams = new RunParams(); //前置机运行参数 + public static MeterTimingParams meterTimingParams = new MeterTimingParams();//定采运行参数 + public static OpcDeviceParams opcDeviceParams = new OpcDeviceParams();// opc客户端运行参数 + + private static String clazzName = new Object() { + public String getClassName() + { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /** 获取定采工作配置参数 */ + public static MeterTimingParams GetMeterTiming() { + + meterTimingParams.reSend = 3; //错误重发次数 + meterTimingParams.parallel = 30; //并发次数 + meterTimingParams.logSet = 2; //巡检日志工作状态 0 不记录 1 记录错误 2 全部记录 + meterTimingParams.intervalTiming = 30;//运行间隔时间(补抄) 单位:分钟 + meterTimingParams.runNum = 8; + meterTimingParams.density = 1;//曲线抄表间隔 + + int i,j; + String str; + String strsql = "SELECT code,content FROM syscode WHERE type=2 AND code>'0000' ORDER BY code"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->读取定采工作配置参数不成功!"); + return null; + } + try { + while (rSet.next()) { + str = rSet.getString("code"); + str = str.trim(); + i = Integer.valueOf(str); + str = rSet.getString("content"); + + switch(i) + { + case 1://错误重发次数 + meterTimingParams.reSend = Integer.valueOf(str); + break; + case 2://并发次数 + meterTimingParams.parallel = Integer.valueOf(str); + break; + case 3://巡检日志工作状态 0 不记录 1 记录错误 2 全部记录 + meterTimingParams.logSet = Integer.valueOf(str); + break; + case 4://开始时间 格式: HH:MM + meterTimingParams.firstRunTime = str; + break; + case 5://运行间隔时间 单位:分钟 + meterTimingParams.intervalTiming = Integer.valueOf(str); + break; + case 6://每天运行次数 + meterTimingParams.runNum = Integer.valueOf(str); + break; + case 7://曲线密度 0:不冻结 1:15 2:30 3:60 254:5 255:1 + meterTimingParams.density = Integer.valueOf(str); + break; + case 8://通信包大小 + meterTimingParams.packsize = Integer.valueOf(str); + break; + case 9://光感控制-照度变化阀值 + meterTimingParams.luxChangeLimit = Long.valueOf(str); + break; + } + + } + } catch (SQLException e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return meterTimingParams; + } + + /** 获取电表定采工作设置参数 */ + public static String GetPowerTiming() { + String result = ""; + String content[] = new String[4]; + content[0] = "1"; //数据冻结密度(m)(1:15分钟;2:30分钟;3:60分钟) + content[1] = "3"; //补抄次数 + content[2] = "06"; //日冻结数据抄读时间(整点) 格式:HH + Object[] objects; + String str; + int i,j; + String strsql = "SELECT code, content FROM syscode WHERE type=62 AND code>'0000' ORDER BY code"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + str = rSet.getString("code"); + str = str.trim(); + i = Integer.valueOf(str); + content[i - 1] = rSet.getString("content"); + } + } catch (SQLException e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + for ( j = 0; j < content.length; j++) { + if (j==0) + result = content[j]; + else + result = result + '|' + content[j]; + } + return result; + } + + //运行参数结构体 + + + /*配置参数 */ + public static RunParams GetPostParams() { + runParams.gprsIp = "1.190.175.75";//GPRS服务器IP (黑龙电服务器) + runParams.gprsPort = 3040;//GPRS服务器端口 + + runParams.gprsIpLon = "1.190.175.75";//GPRS服务器IP (黑龙服务器) + runParams.gprsPortLon = 3040;//GPRS服务器端口 + + runParams.reSend =1; //错误重发次数 + runParams.gprsTimeOut = 60000;//GPRS超时时间(单位:毫秒) + runParams.timeDiscard = 120;//指令超时不处理时间(单位:秒) + runParams.threadsize = 200;//指令转发处理线程池线程数 + runParams.intervalEvent = 1;//数据报文解析处理间隔时间(单位:分钟) + runParams.intervalScan = 20;//检测线程池线程运行状态间隔时间 + runParams.terminalCom = "com1" ;//集中器串口 + + //获取语言 + try { + //InputStream ins = new FileInputStream(System.getProperty("user.dir") + "\\conn.properties"); + InputStream ins = SQLHelper.class.getClassLoader().getResourceAsStream("conn.properties"); + Properties p = new Properties(); + p.load(ins); + runParams.language = p.getProperty("language"); + runParams.opcControl = Boolean.valueOf(p.getProperty("opcControl"));//光控转发处理 + runParams.MControlTiming15 = Boolean.valueOf(p.getProperty("MControlTiming15"));//线路开关 15分钟定时抄读任务 + runParams.MControlTiming60 = Boolean.valueOf(p.getProperty("MControlTiming60"));//线路开关 60分钟定时抄读任务 + runParams.LampTiming = Boolean.valueOf(p.getProperty("LampTiming"));//路灯曲线 抄读任务 + runParams.ForWard485 = Boolean.valueOf(p.getProperty("ForWard485"));//485转发 抄读任务 + runParams.LampDay3761Timing = Boolean.valueOf(p.getProperty("LampDay3761Timing"));//灯具 日冻结 抄读任务 + runParams.TerminalDay3761Timing = Boolean.valueOf(p.getProperty("TerminalDay3761Timing"));//集中器 日冻结 抄读任务 + runParams.AnalysisOfTunnelElectricity = Boolean.valueOf(p.getProperty("AnalysisOfTunnelElectricity"));//隧道电量分析 + runParams.gprsIp = p.getProperty("gprsIp"); + runParams.gprsPort = 2030; + } catch (IOException e) { + // TODO Auto-generated catch block + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + int i,j; + String strsql = "SELECT code,content FROM syscode WHERE type=60 AND code>'0000' ORDER BY code"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + if (runParams.language.equals("en")) + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Read the frontend configuration parameter is not successful!"); + else + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->读取前置机配置参数不成功!"); + return runParams; + } + String str; + try { + while (rSet.next()) { + str = rSet.getString("code"); + str = str.trim(); + i = Integer.valueOf(str); + str = rSet.getString("content").trim(); + switch (i) { + case 1: //GPRS服务器 + runParams.gprsIp = str; + break; + case 2://GPRS服务器端口 + runParams.gprsPort = Integer.valueOf(str); + break; + case 3://错误重发次数千 + runParams.reSend = Integer.valueOf(str); + break; + case 4://GPRS通信超时时间(单位:毫秒) + runParams.gprsTimeOut = Integer.valueOf(str); + break; + case 5://指令超时不处理时间(单位:秒) + runParams.timeDiscard = Integer.valueOf(str); + break; + case 6://指转发处理线程池大小 + runParams.threadsize = Integer.valueOf(str); + break; + case 7://事件处理间隔(单位:分钟) + runParams.intervalEvent = Integer.valueOf(str); + break; + case 8://检测试线程运行间隔(单位:分钟) + runParams.intervalScan = Integer.valueOf(str); + break; + case 9://本地串口通信端口(例:com1) + runParams.terminalCom = str.toUpperCase(); + break; + case 10://串口通信超时时间 + runParams.comTimeOut = Integer.valueOf(str); + break; + + case 11://485总线通信口 + runParams.terminalCom485 = str.toUpperCase(); + break; + case 12://485集中器心跳周期 + runParams.beat485 = Integer.valueOf(str); + break; + case 13://485集中器命令超时时间 + runParams.comTimeOut485 = Integer.valueOf(str); + break; + case 15: {// 设备数据同步周期(单位:秒) + runParams.devideSyncTime = Integer.valueOf(str); + break; + } + case 16: {// websocket ip + runParams.websocketIp = str; + break; + } + case 17: {// websocket port + runParams.websocketPort = Integer.valueOf(str); + break; + } + case 18: { // 车检器连接IP + runParams.carCheckSocketIp = str; + break; + } + case 19: {// 车检器连接端口 + runParams.carCheckSocketPort = Integer.valueOf(str); + break; + } + case 20: { + runParams.carCheckSocketTimeOut = Integer.valueOf(str); + break; + } + case 21: { + runParams.carCheckSocketSaveInteval = Integer.valueOf(str); + break; + } + + case 30: //GPRS服务器 Lon16 + runParams.gprsIpLon = str; + break; + case 31://GPRS服务器端口 Lon16 + runParams.gprsPortLon = Integer.valueOf(str); + break; + default: + break; + } + } + } catch (Exception e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + String strsql2 = "SELECT code,content FROM syscode WHERE type=100 AND code>'0000' ORDER BY code"; + java.sql.Statement stmt2 = null; + ResultSet rSet2 = SQLHelper.getResultSet(strsql2); + if (rSet2 == null) { + if (runParams.language.equals("en")) + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Read the frontend configuration parameter is not successful!"); + else + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->读取前置机配置参数不成功!"); + return runParams; + } + String str2; + try { + while (rSet2.next()) { + str2 = rSet2.getString("code"); + str2 = str2.trim(); + i = Integer.valueOf(str2); + str2 = rSet2.getString("content").trim(); + switch (i) { + case 2: {// 车检器是否开启 + runParams.carCheckSocketIsOpen = "0".equals(str2)?false:true; + break; + } + } + } + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + stmt2 = rSet2.getStatement(); + rSet2.close(); + stmt2.close(); + rSet2 = null; + stmt2 = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return runParams; + } + + /** + * opc配置参数 + * @return + */ + public static OpcDeviceParams GetOpcDeviceParams() { + opcDeviceParams.opcIp = "127.0.0.1"; + opcDeviceParams.opcPort = "49320"; + opcDeviceParams.opcTimeOut = 30; + + String strsql = "SELECT code,content FROM syscode WHERE type=25 AND code>'0000' ORDER BY code"; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + if (runParams.language.equals("en")) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Read the frontend configuration parameter is not successful!"); + } else { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->读取前置机配置参数不成功!"); + } + return opcDeviceParams; + } + + String str; + int i,j; + try { + while (rSet.next()) { + str = rSet.getString("code"); + str = str.trim(); + i = Integer.valueOf(str); + str = rSet.getString("content").trim(); + switch (i) { + case 1: + opcDeviceParams.enable = "0".equals(str)?false:true; + case 2: + opcDeviceParams.opcIp = str; + break; + case 3: + opcDeviceParams.opcPort = str; + break; + case 4: + opcDeviceParams.opcUserName = str; + break; + case 5: + opcDeviceParams.opcPassword = str; + break; + case 6: + opcDeviceParams.opcCycleTime = Integer.valueOf(str); + break; + case 7: + opcDeviceParams.opcTimeOut = Integer.valueOf(str); + break; + + default: + break; + } + } + } catch (Exception e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + return opcDeviceParams; + } + + /** 获取短信猫配置参数 */ + public static String getSmsParams() { + String result = ""; + String strsql = "SELECT content FROM syscode WHERE type=61 AND code='0004' ORDER BY code"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->读取短信猫配置参数不成功!"); + return ""; + } + try { + while (rSet.next()) { + result = result + rSet.getString("content") + "|"; + } + } catch (Exception e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + if (!result.equals("")) { + result = result.substring(0, result.length() - 1); + } + return result; + } + + /** 获取短信信息中心号码 */ + public static String getenter() { + String center = ""; + String strsql = "select content from syscode where type=61 and code='0001'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + center = rSet.getString("content"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return center; + } + + /** 获取短信息最大发送次数 */ + public static int getmaxCount() { + int count = 0; + String strsql = "select content from syscode where type=61 and code='0003'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return 0; + } + try { + while (rSet.next()) { + count = rSet.getInt("content"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return count; + } + + /** 获取短信猫连接口参数 */ + public static String smsport() { + String serialport = ""; + String strsql = "select content from syscode where type=61 and code='0002'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + serialport = rSet.getString("content"); + } + } catch (SQLException e) { + Log.writelog(SystemParameter.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return serialport.toUpperCase(); + } +} diff --git a/common/src/main/java/com/back/threadpool/ThreadPool.java b/common/src/main/java/com/back/threadpool/ThreadPool.java new file mode 100644 index 0000000..122215a --- /dev/null +++ b/common/src/main/java/com/back/threadpool/ThreadPool.java @@ -0,0 +1,336 @@ +package com.back.threadpool; + +import com.back.action.Log; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class ThreadPool extends ThreadGroup { + private boolean isClosed = false; // 线程池是否关闭 + private LinkedList workRun; // 工作队列 + private LinkedList workQueue; // 工作后继队列 + private String threadPoollanguage; + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + public static ArrayList terminaList = new ArrayList(); + + public static ThreadPool Instance; // 唯一实例 + + public static ThreadPool getInstance(int poolSize, String language) { + if (Instance == null) { + Instance = new ThreadPool(poolSize, language); + } + + return Instance; + } + + private ThreadPool(int poolSize, String language) { // poolSize 表示线程池中的工作线程的数量 + super("1"); // 指定ThreadGroup的名称 + setDaemon(true); // 继承到的方法,设置是否守护线程池 + workQueue = new LinkedList(); // 创建工作后继队列 + workRun = new LinkedList(); // 创建工作队列 + + threadPoollanguage = language; + + if (language.equals("en")) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Create a thread pool(" + String.valueOf(poolSize) + ")......"); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Start the thread pool(" + String.valueOf(poolSize) + ")......"); + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->创建线程池(" + String.valueOf(poolSize) + ")......"); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->启动线程池(" + String.valueOf(poolSize) + ")......"); + } + + for (int i = 0; i < poolSize; i++) { + new WorkThread(i, language).start(); // 创建并启动工作线程,线程池数量是多少就创建多少个工作线程 + } + if (language.equals("en")) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Thread start to finish! "); + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->线程启动完成! "); + } + + } + + /** 获取备用任务队列的数量 */ + public int GetWorkSize() { + return workQueue.size(); + } + + public synchronized void terminaListRemove(String terminal) { + // Log.writelog(clazzName,terminal); + terminaList.remove(terminal); + if (workQueue.size()>0) + notify(); + } + + /** 向工作队列中加入一个新任务,由工作线程去执行该任务 */ + public synchronized void execute(String terminal, int cmdid, Thread task) { + if (isClosed) { + throw new IllegalStateException(); + } + if (task != null) { + task.setName(terminal); + // workQueue.add(task);// 向队列中加入一个任务 + if (terminaList.contains(terminal)) { + if (cmdid != 0) {// 优先处理页面指令 + workQueue.add(0, task); + } else { + workQueue.add(task);// 向队列中加入一个任务 + } + if (threadPoollanguage.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + ":" + String.valueOf(task.getId()) + ":" + cmdid + "]:" + + "To join the thread pool"); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + ":" + String.valueOf(task.getId()) + ":" + cmdid + "]:" + "加入线程池"); + } else {// 立即执行 + terminaList.add(terminal); + workRun.add(task); + + if (threadPoollanguage.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + ":" + String.valueOf(task.getId()) + ":" + cmdid + "]:" + + "To join the thread pool(Run Now)"); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + ":" + String.valueOf(task.getId()) + ":" + cmdid + "]:" + "加入线程池(立即执行)"); + } + + notify(); // 唤醒正在getTask()方法中等待任务的工作线程 + } + } + + /** 从工作队列中取出一个任务,工作线程会调用此方法(同步调用的) */ + private synchronized Thread getTask(int threadid) { + Thread thread; + String add; + int count =0; + while (workRun.size() == 0) { // 及时处理页面命令 + if (isClosed) + return null; + + if (workQueue.size() != 0) { // 从备用队列中取出放到运行队列中 + try { + count = 0; + for (int i = 0; i < workQueue.size(); i++) { + if (workRun.size() > 0) + break; // 及时处理页面命令 + thread = workQueue.get(i); + add = thread.getName(); + if (!terminaList.contains(add)) { + if (count == 0) { + terminaList.add(add); + workRun.add(thread); + workQueue.remove(i); + count++; + break; + } + } + } + + /* + if (workRun.size() > 0) + { + notifyAll();//notifyAll + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool.getTask():workRun.size-->" + workRun.size() + " workQueue.size-->" + workQueue.size() ); + + } + if (workQueue.size()==0) + { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool.getTask(): workQueue.size-->0" + workQueue.size() ); + + } + */ + + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool.getTask("+String.valueOf(threadid)+"):workRun.size-->" + workRun.size() + " workQueue.size-->" + workQueue.size() ); + if (count > 0) // 2012-03-08 需要唤醒正在getTask()方法中等待任务的工作线程 + break; + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool.getTask():ERROR-->" + e.getMessage()); + } + + + + }// if (workQueue.size() != 0) + + if (count > 0) // 2012-03-08 需要唤醒正在getTask()方法中等待任务的工作线程 + break; + + try { + // Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->"+String.valueOf(threadid)+" 任务队列为空! 等待任务任务"); + wait();// 如果工作队列中没有任务,就等待任务 + //Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->任务队列为空! 等待任务任务"); + } catch (InterruptedException e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool.getTask():ERROR1-->" + e.getMessage()); + } + + + + }// while (workRun.size() == 0) { + + // 2012-03-08 防止线程没有被唤醒 + /* + for (int i = 0; i < workQueue.size(); i++) { + thread = workQueue.get(i); + add = thread.getName(); + if (!terminaList.contains(add)) { + notify(); + break; + } + } + */ + if (workQueue.size()>0) + notify(); + if (threadPoollanguage.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + threadid + "]Began to perform a task..."); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + threadid + "]开始执行任务..."); + + return (Thread) workRun.removeFirst(); // 返回队列中第一个元素,并从队列中删除 + } + + /** 关闭线程池 */ + public synchronized void closePool() { + if (!isClosed) { + waitFinish(); // 等待工作线程执行完毕 + isClosed = true; + workRun.clear(); // 清空工作队列 + interrupt(); // 中断线程池中的所有的工作线程,此方法继承自ThreadGroup类 + } + + if (threadPoollanguage.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Close the thread pool......"); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->关闭线程池......"); + } + + /** 等待工作线程把所有任务执行完毕 */ + public void waitFinish() { + synchronized (this) { + isClosed = true; + notifyAll(); // 唤醒所有还在getTask()方法中等待任务的工作线程 + } + Thread[] threads = new Thread[activeCount()]; // activeCount() + int count = enumerate(threads); // enumerate()方法继承自ThreadGroup类,根据活动线程的估计值获得线程组中当前所有活动的工作线程 + for (int i = 0; i < count; i++) { // 等待所有工作线程结束 + try { + threads[i].join(); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } + + /** 监控线程池,处于堵塞状态的线程终止重建 */ + public void scanthread(String language) { + Thread[] threads = new Thread[activeCount()]; + int count = enumerate(threads); + + for (int i = 0; i < count; i++) { + if (threads[i] != null && threads[i].isAlive()) { + try { + if (threads[i].getState().toString().equals("BLOCKED")) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + threads[i].getName() + "," + threads[i].getState()); + threads[i].interrupt();// 中断线程 + threads[i].join(30000);// 等待线程终止的时间最长为 30000 毫秒 + try { + if (threads[i].isAlive()) { + threads[i].stop(); + } + } catch (Exception e) { + } + threads[i] = null; + new WorkThread(i, language).start();// 创建新线程 + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->CreateThread" + threads[i].getName()); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->创建线程" + threads[i].getName()); + } + } catch (Throwable e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ThreadPool-->scanthread():ERROR" + e.toString()); + } + } + } + } + + /** 内部类,工作线程,负责从工作队列中取出任务,并执行 */ + private class WorkThread extends Thread { + private int id; + private String language; + + public WorkThread(int id, String language) { + // 父类构造方法,将线程加入到当前ThreadPool线程组中 + super(ThreadPool.this, id + ""); + this.id = id; + this.language = language; + } + + public void run() { + while (!isInterrupted()) { // isInterrupted()方法继承自Thread类,判断线程是否被中断 + Thread task = null; + task = getTask(id); // 取出任务 + try { + Thread.sleep(50); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // 如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程 + if (task == null) + return; + + try { + String add = task.getName(); + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + add + "]Fetch-and-execute!" + id); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + add + "]取出执行!" + id); + + task.start(); // 运行任务 + + // terminaList.remove(add); + + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + add + "]End Sub!" + id); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + add + "]执行结束!" + id); + + } catch (Throwable t) { + t.printStackTrace(); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->WorkThread.run():ERROR-->" + t.getMessage()); + } + // task.destroy(); + task = null;// 2012 02 20 wwb增加防止内存溢出 + + } + } + } +} \ No newline at end of file diff --git a/common/src/main/resources/conn.properties b/common/src/main/resources/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/common/src/main/resources/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/common/target/classes/META-INF/MANIFEST.MF b/common/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..bd2d96f --- /dev/null +++ b/common/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: Administrator +Build-Jdk: 1.8.0_351 +Created-By: Maven Integration for Eclipse + diff --git a/common/target/classes/META-INF/maven/com.back/common/pom.properties b/common/target/classes/META-INF/maven/com.back/common/pom.properties new file mode 100644 index 0000000..d3fd987 --- /dev/null +++ b/common/target/classes/META-INF/maven/com.back/common/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Jun 05 23:14:47 CST 2024 +version=0.0.1-SNAPSHOT +groupId=com.back +m2e.projectName=2-common +m2e.projectLocation=D\:\\fyj_20240312\\processor\\common +artifactId=common diff --git a/common/target/classes/META-INF/maven/com.back/common/pom.xml b/common/target/classes/META-INF/maven/com.back/common/pom.xml new file mode 100644 index 0000000..3ef61a2 --- /dev/null +++ b/common/target/classes/META-INF/maven/com.back/common/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + common + jar + + + + + org.apache.commons + commons-lang3 + 3.8 + + + + com.alibaba + fastjson + 1.2.66 + + + + mysql + mysql-connector-java + 5.1.40 + + + + org.slf4j + slf4j-api + 1.7.25 + + + + + org.apache.httpcomponents + httpclient + 4.5.6 + + + + com.google.code.gson + gson + 2.8.9 + + + + + org.bidib.jbidib.org.qbang.rxtx + rxtxcomm + 2.2 + + + + org.scream3r + jssc + 2.8.0 + + + + com.sun.mail + javax.mail + 1.6.2 + + + + + + + org.eclipse.milo + sdk-client + 0.6.3 + + + + org.java-websocket + Java-WebSocket + 1.5.3 + + + + \ No newline at end of file diff --git a/common/target/classes/conn.properties b/common/target/classes/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/common/target/classes/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/opc/conn.properties b/opc/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/opc/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/opc/pom.xml b/opc/pom.xml new file mode 100644 index 0000000..cd0d315 --- /dev/null +++ b/opc/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + opc + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/opc/src/main/java/com/back/action/Work.java b/opc/src/main/java/com/back/action/Work.java new file mode 100644 index 0000000..0bc5432 --- /dev/null +++ b/opc/src/main/java/com/back/action/Work.java @@ -0,0 +1,353 @@ +package com.back.action; + +import com.back.common.RunParams; +import com.back.jdbc.SQLHelper; +import com.back.opcua.OpcUaUtil; +import com.back.protocol.Protocol; +import com.back.protocol.SystemParameter; +import com.back.threadpool.ThreadPool; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Work { + + private static ThreadPool threadPool; + + private static int threadsize; + public static String language = ""; // 语言 + + public static RunParams runParams; + + private static int timeDiscard;// 超时不处理时间(秒) + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + + + public Work() { + SystemParameter.GetPostParams(); + runParams = SystemParameter.runParams; + // 转发参数设置 + + threadsize = SystemParameter.runParams.threadsize; + + timeDiscard = SystemParameter.runParams.timeDiscard; + + language = SystemParameter.runParams.language; + + threadPool = ThreadPool.getInstance(threadsize, language);// 创建线程池 + + try { + Thread.sleep(500);// 休眠500毫秒,以便让线程池中的工作线程全部运行 + } catch (InterruptedException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + public void opcDeviceDataSync() { + Reconnect(); + // 查询第三方设备最新数据 + String sql = " SELECT * from (SELECT * from opcdevicedata HAVING 1 ORDER BY _TIMESTAMP DESC) tmp GROUP BY _NAME "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(sql); + if (rSet == null) { + return; + } + + Map deviceMap = new HashMap<>(); + try { + System.out.println("查询总计:"+rSet.getRow()); + while (rSet.next()) { + String name = rSet.getString("_NAME"); + String value = rSet.getString("_VALUE"); + String timestamp = rSet.getString("_TIMESTAMP").substring(0, 19); +// System.out.println(name + ":" + value + ":" + timestamp); + String[] opcNameArray = name.split("\\."); + + String devicechannel = opcNameArray[0]; + String devicename = opcNameArray[1]; + + List labelNameList = new ArrayList<>(); + String opcDeviceSql = "SELECT opcdevicechannel,opcdevicename,comid,s.remark remark,s.content content FROM opcdevice o LEFT JOIN syscode s ON s.type = '26' " + + "and o.opcdevicetype = s.code where opcdevicechannel = '" + devicechannel + "' and opcdevicename = '" + devicename + "'"; + ResultSet opcDeviceSet = SQLHelper.getResultSet(opcDeviceSql); + if (opcDeviceSet != null) { + while (opcDeviceSet.next()) { + String content = opcDeviceSet.getString("content"); + String comid = opcDeviceSet.getString("comid"); + String syscodeSql = "SELECT code,content,encontent FROM syscode WHERE type='" + content + "' AND code>'0000' ORDER BY code"; + ResultSet syscodeSet = SQLHelper.getResultSet(syscodeSql); + if (syscodeSet != null) { + while (syscodeSet.next()) { + String syscodeContent = syscodeSet.getString("encontent"); +// opcNameStrList.add(devicechannel + "." + devicename + "." + syscodeContent); + labelNameList.add(syscodeContent + "_" + comid); + } + } + } + } +// System.out.println(JSON.toJSONString(labelNameList)); + + OpcDeviceData opcDeviceData = null; + if (deviceMap.get(opcNameArray[0] + "." + opcNameArray[1]) == null) { + opcDeviceData = new OpcDeviceData(); + } else { + opcDeviceData = deviceMap.get(opcNameArray[0] + "." + opcNameArray[1]); + } + opcDeviceData.setOpcdevicechannel(opcNameArray[0]); + opcDeviceData.setOpcdevicename(opcNameArray[1]); + if (name.endsWith("_System._Error")) { + int online = Integer.valueOf(value) == 0 ? 1 : 0; + opcDeviceData.setOnline(online); + } + if (labelNameList.contains(opcNameArray[2].trim())) { + if (opcNameArray[2].startsWith("SENSOR_DATAI_LT")) { + opcDeviceData.setLux(value); + } else if (opcNameArray[2].startsWith("LOOP_DI_OPEN")) { + opcDeviceData.setLoopon(value); + } else if (opcNameArray[2].startsWith("LOOP_DI_CLOSE")) { + opcDeviceData.setLoopoff(value); + } else if (opcNameArray[2].startsWith("LOOP_DI_HAND")) { + opcDeviceData.setControlstate(value); + } else if (opcNameArray[2].startsWith("LOOP_DI_STATUS")) { + opcDeviceData.setLoopDiStatus(value); + } + } + if (opcDeviceData.getDatatime() == null + || StringUtils.isNoneEmpty(opcDeviceData.getDatatime()) && LocalDateTime.parse(opcDeviceData.getDatatime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).isBefore(LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))) { + opcDeviceData.setDatatime(timestamp); + } + deviceMap.put(opcNameArray[0] + "." + opcNameArray[1], opcDeviceData); + + } + + if (deviceMap.size() > 0) { + for (Map.Entry entry : deviceMap.entrySet()) { + String key = entry.getKey(); + OpcDeviceData deviceData = entry.getValue(); +// System.out.println(JSON.toJSONString(deviceData)); + + String updateSql = null; + if (deviceData.getOnline() != null && Integer.valueOf(deviceData.getOnline()) == 1) { + updateSql = "update opcdevice set online = '1', datatime = '" + deviceData.getDatatime() + "' "; + if (deviceData.getLux() == null) { + updateSql += ",LOOP_DI_STATUS = " + deviceData.getLoopDiStatus(); + } else { + updateSql += ",SENSOR_DATAI_LT = " + deviceData.getLux(); + } + updateSql += " where opcdevicechannel = '" + deviceData.getOpcdevicechannel() + "' and opcdevicename = '" + deviceData.getOpcdevicename() + "'"; + } else { + updateSql = "update opcdevice set online = '0', datatime = '" + deviceData.getDatatime() + "' " + + "where opcdevicechannel = '" + deviceData.getOpcdevicechannel() + "' and opcdevicename = '" + deviceData.getOpcdevicename() + "'"; + } + + if (StringUtils.isNotEmpty(updateSql)) { + SQLHelper.ExecSql(updateSql); + } + } +// String updateSql = null; +// if (name.endsWith("_System._Error")) { +// int online = Integer.valueOf(value) == 0 ? 1 : 0; +// updateSql = "update opcdevice set online = '" + online + "', datatime = '" + timestamp + "' where opcdevicechannel = '" + opcNameArray[0] + "' and opcdevicename = '" + opcNameArray[1] + "'"; +// } +// +// if ("传感值".equals(opcNameArray[2])) { +// updateSql = "update opcdevice set online = '" + online + "', datatime = '" + timestamp + "' where opcdevicechannel = '" + opcNameArray[0] + "' and opcdevicename = '" + opcNameArray[1] + "'"; +// } + } + + + } catch (SQLException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + + + + + private class OpcDeviceData { + private String opcdevicechannel; + private String opcdevicename; + private Integer online; + private String loopon; + private String loopoff; + private String loopDiStatus; + private String controlstate; + private String lux; + private String datatime; + + public String getOpcdevicechannel() { + return opcdevicechannel; + } + public void setOpcdevicechannel(String opcdevicechannel) { + this.opcdevicechannel = opcdevicechannel; + } + public String getOpcdevicename() { + return opcdevicename; + } + public void setOpcdevicename(String opcdevicename) { + this.opcdevicename = opcdevicename; + } + public Integer getOnline() { + return online; + } + public void setOnline(Integer online) { + this.online = online; + } + public String getLoopon() { + return loopon; + } + public void setLoopon(String loopon) { + this.loopon = loopon; + } + public String getLoopoff() { + return loopoff; + } + public void setLoopoff(String loopoff) { + this.loopoff = loopoff; + } + public String getDatatime() { + return datatime; + } + public void setDatatime(String datatime) { + this.datatime = datatime; + } + public String getControlstate() { + return controlstate; + } + public void setControlstate(String controlstate) { + this.controlstate = controlstate; + } + public String getLux() { + return lux; + } + public void setLux(String lux) { + this.lux = lux; + } + public String getLoopDiStatus() { + return loopDiStatus; + } + public void setLoopDiStatus(String loopDiStatus) { + this.loopDiStatus = loopDiStatus; + } + } + + + /** 清空连接 */ + public synchronized static void Reconnect() { + if (SQLHelper.isclose == true) { + SQLHelper.closeconn(); + } + } + + + /** OPC转发指令 操作 */ + public void ForWardOpc() { + Reconnect(); + int i = 0; + + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + String strsql = "SELECT CommandID,terminal,cmdcode,comtype,ruletype,wtime,responsetype FROM commands "; + + // 0001 和 0002 自研发、 0003 OPC + strsql += " WHERE TIMESTAMPDIFF(SECOND, WTime, NOW())<" + timeDiscard + + " and Status=0 and comtype='0003' LIMIT " + threadsize; + + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.ExecProcwCommands(strsql); + if (rSet == null) { + return; + } + + try { + while (rSet.next()) { + + int cmdid = rSet.getInt("CommandID"); + String terminal = rSet.getString("terminal"); + String cmdcode = rSet.getString("cmdcode"); + String ruletype = rSet.getString("ruletype"); + String wtime = rSet.getString("wtime"); + String responsetype = rSet.getString("responsetype"); + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminal + "] "); + Protocol.updateCommands(terminal, cmdid); // 更新指令表读取标识 + + boolean send = true; + String syncSql = "SELECT datasynciseffect FROM DataSync d LEFT JOIN terminals t " + + "ON d.terminalid = t.id WHERE t.comid = " + terminal; + try { + ResultSet resultSet = SQLHelper.getResultSet(syncSql); + while (resultSet.next()) { + int data = resultSet.getInt("datasynciseffect"); + if (data == 1) { + String remark = "Sync Busy"; + SQLHelper.ExecProcwreceivedata(cmdid, terminal, null, 5, remark); + send = false; + } + } + } catch (SQLException e) { + Log.writelog1("Sql 查询出错,syncSql: " + syncSql); + e.printStackTrace(); + } + + // 配电箱编号为 null,则为第三方设备命令发送 + //if (StringUtils.isEmpty(terminal)) { + // 命令使用英文逗号分隔符 + String[] cmdCodeArray = cmdcode.split(","); + String operation = cmdCodeArray[0]; + String identifier = cmdCodeArray[1].trim(); + + OpcUaClient opcUaClient = OpcUaUtil.opcUaClient; + // 打开连接 + opcUaClient.connect().get(); + String result = null; + if (operation.equals("readopc")) { + result = OpcUaUtil.readNode(opcUaClient, identifier); + } else if (operation.equals("writeopc")) { + result = OpcUaUtil.writeNodeValue(opcUaClient, identifier, Short.valueOf(cmdCodeArray[2].trim())); +// result = writeResult ? "true" : "false"; + } + // 关闭连接 + opcUaClient.disconnect().get(); + SQLHelper.ExecProcwreceivedata(cmdid, null, cmdcode + "," + result, 5, "opc device cmd"); + //} + + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: "); + } + } +} diff --git a/opc/src/main/java/com/back/main/MainProcess.java b/opc/src/main/java/com/back/main/MainProcess.java new file mode 100644 index 0000000..98bd10c --- /dev/null +++ b/opc/src/main/java/com/back/main/MainProcess.java @@ -0,0 +1,51 @@ +package com.back.main; + +import com.back.action.Work; +import com.back.common.OpcDeviceParams; +import com.back.opcua.OpcUaUtil; +import com.back.protocol.SystemParameter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Timer; +import java.util.TimerTask; + +public class MainProcess { + + private static Work work = new Work(); + + public static final Logger LOGGER = LoggerFactory.getLogger(MainProcess.class); + + public static void main(String[] args) { + + System.out.println("ver 1.2.11 2019-03-24 17");// 英文 + + OpcDeviceParams opcDeviceParams = SystemParameter.GetOpcDeviceParams(); + if (opcDeviceParams == null) { + System.out.println("Database connection failed!"); + } + String opcIp = opcDeviceParams.opcIp; + String opcPort = opcDeviceParams.opcPort; + int opcCycleTime = opcDeviceParams.opcCycleTime; + int opcTimeOut = opcDeviceParams.opcTimeOut; + + try { + OpcUaUtil.createClient(opcIp, opcPort, opcTimeOut); + } catch (Exception e) { + System.err.println("opc ua client start error, msg:%s" + e.getMessage()); + } + + //发送opc命令 + MythreadOpc myopc = new MythreadOpc(); + Thread opc = new Thread(myopc); + opc.start(); + + Timer opcDeviceDataSyncTimer = new Timer(); + opcDeviceDataSyncTimer.schedule(new TimerTask() { + public void run() { + work.opcDeviceDataSync(); + } + }, 0, opcCycleTime * 1000); + + } +} diff --git a/opc/src/main/java/com/back/main/MythreadOpc.java b/opc/src/main/java/com/back/main/MythreadOpc.java new file mode 100644 index 0000000..47113bb --- /dev/null +++ b/opc/src/main/java/com/back/main/MythreadOpc.java @@ -0,0 +1,38 @@ +package com.back.main; + +import com.back.action.Log; +import com.back.action.Work; + +public class MythreadOpc implements Runnable{ + + private Work work = new Work(); + + private String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + + @Override + public void run() { + int i = 0; + while (true) { + + i++; + if (i > 600) { + i = 0; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ForWardGprs() Run!"); + } + try { + Thread.sleep(100); + work.ForWardOpc(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } +} diff --git a/opc/src/main/java/com/back/opcua/OpcUaUtil.java b/opc/src/main/java/com/back/opcua/OpcUaUtil.java new file mode 100644 index 0000000..e757501 --- /dev/null +++ b/opc/src/main/java/com/back/opcua/OpcUaUtil.java @@ -0,0 +1,150 @@ +package com.back.opcua; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider; +import org.eclipse.milo.opcua.sdk.client.nodes.UaNode; +import org.eclipse.milo.opcua.stack.core.Identifiers; +import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; +import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText; +import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; +import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode; +import org.eclipse.milo.opcua.stack.core.types.builtin.Variant; +import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger; +import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn; +import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription; +import org.jetbrains.annotations.Nullable; + +import com.back.action.Log; + +public class OpcUaUtil { + + private static String clazzName = new Object() { + public String getClassName() + { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public static OpcUaClient opcUaClient; + /** + * 创建OPC UA客户端 + * @return + * @throws Exception + */ + public static OpcUaClient createClient(String ip, String port, int timeout) throws Exception { + String endPointUrl = String.format("opc.tcp://%s:%s", ip, port); + opcUaClient = OpcUaClient.create( + endPointUrl, + endpointDescriptions -> { + final List collect = endpointDescriptions.stream().collect(Collectors.toList()); + final Optional first = endpointDescriptions + .stream() + .findFirst(); + System.out.println(first.get().getSecurityPolicyUri()); + return Optional.of(collect.get(0)); + }, + configBuilder -> + configBuilder + .setApplicationName(LocalizedText.english("opc-ua client")) + .setApplicationUri(endPointUrl) +// .setIdentityProvider(new UsernameProvider(username, password)) + .setIdentityProvider(new AnonymousProvider()) + .setRequestTimeout(UInteger.valueOf(timeout * 1000)) + .build() + ); + Log.writelog(OpcUaUtil.clazzName, String.format("创建客户端:%s 成功!", opcUaClient)); + return opcUaClient; + } + + /** + * 遍历树形节点 + * + * @param client OPC UA客户端 + * @param uaNode 节点 + * @throws Exception + */ + public static void browseNode(OpcUaClient client, UaNode uaNode) throws Exception { + List nodes; + if (uaNode == null) { + nodes = client.getAddressSpace().browseNodes(Identifiers.ObjectsFolder); + } else { + nodes = client.getAddressSpace().browseNodes(uaNode); + } + for (UaNode nd : nodes) { + //排除系统行性节点,这些系统性节点名称一般都是以"_"开头 + if (Objects.requireNonNull(nd.getBrowseName().getName()).contains("_")) { + continue; + } + System.out.println("Node= " + nd.getBrowseName().getName() + "_" + nd.getNodeId().getNamespaceIndex()); + browseNode(client, nd); + } + } + + + /** + * 读取节点数据 + * + * @param client OPC UA客户端 + * @throws Exception + */ + public static String readNode(OpcUaClient client, String identifier) throws Exception { + try { + int namespaceIndex = 2; + //节点 + NodeId nodeId = new NodeId(namespaceIndex, identifier); + //读取节点数据 + DataValue value = client.readValue(0.0, TimestampsToReturn.Neither, nodeId).get(); + //标识符 + String identifier1 = String.valueOf(nodeId.getIdentifier()); + System.out.println(identifier1 + ": " + String.valueOf(value.getValue().getValue())); + + StatusCode statusCode = value.getStatusCode(); + if (statusCode.isGood()) { + return String.format("value[%s]", String.valueOf(value.getValue().getValue())); + } else { + return String.format("error[%s]", String.valueOf(value.getValue().getValue())); + } + } catch (Exception e) { + System.err.println("error msg: " + e.getMessage()); +// return null; + return String.format("error[%s]", null); + } + } + + + /** + * 写入节点数据 + * + * @param client + * @throws Exception + */ + public static String writeNodeValue(OpcUaClient client, String identifier, short value) throws Exception { + try { + //节点 +// NodeId nodeId = new NodeId(2, "gdxs.传感器.传感值"); + NodeId nodeId = new NodeId(2, identifier); + //创建数据对象,此处的数据对象一定要定义类型,不然会出现类型错误,导致无法写入 + DataValue nowValue = new DataValue(new Variant(value), null, null); + //写入节点数据 + StatusCode statusCode = client.writeValue(nodeId, nowValue).join(); + System.out.println("结果:" + statusCode.isGood()); + if (statusCode.isGood()) { + return String.format("value[%s]", statusCode.isGood()); + } else { + return String.format("error[%s]", statusCode.isGood()); + } + } catch (Exception e) { + System.err.println("writeNode take error, msg: " + e.getMessage()); + return String.format("error[%s]", false); + } + } + + + +} diff --git a/opc/src/main/java/com/back/protocol/Protocol.java b/opc/src/main/java/com/back/protocol/Protocol.java new file mode 100644 index 0000000..e21c77b --- /dev/null +++ b/opc/src/main/java/com/back/protocol/Protocol.java @@ -0,0 +1,66 @@ +package com.back.protocol; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.jdbc.SQLHelper; + + +public class Protocol { + + // ------------------------------------------------------------------系统参数函数------------------------------------------------------------------------------------ + public static SystemParameter systemParameter = new SystemParameter(); + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + static String language = ""; + + public void Setlanguage(String language) { + this.language = language; + } + + + /** 更新指令表读取标识 */ + public static void updateCommands(String terminal, int commandid) { + + System.out.println("\n OPC更新指令表:"); + String strsql = "update commands set status=1,rtime='" + Common.getDateStr0() + "' where CommandID = " + commandid; + int result = SQLHelper.ExecSql(strsql); + // Log.writelog(Protocol.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + // + + // "->[" +strsql); + // int result = SQLHelper.ExecProcwCommands(commandid); + switch (result) { + case -1: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the instruction table data state: failed to update"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:更新失败"); + break; + case -2: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the instruction table data state: failed to connect to the database."); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:连接数据库失败"); + break; + default: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Updated instruction table data status: success"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:更新成功"); + break; + } + } + + +} \ No newline at end of file diff --git a/opc/target/classes/META-INF/MANIFEST.MF b/opc/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..bd2d96f --- /dev/null +++ b/opc/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: Administrator +Build-Jdk: 1.8.0_351 +Created-By: Maven Integration for Eclipse + diff --git a/opc/target/classes/META-INF/maven/com.back/opc/pom.properties b/opc/target/classes/META-INF/maven/com.back/opc/pom.properties new file mode 100644 index 0000000..18996cd --- /dev/null +++ b/opc/target/classes/META-INF/maven/com.back/opc/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Jun 05 23:14:58 CST 2024 +version=0.0.1-SNAPSHOT +groupId=com.back +m2e.projectName=2-opc +m2e.projectLocation=D\:\\fyj_20240312\\processor\\opc +artifactId=opc diff --git a/opc/target/classes/META-INF/maven/com.back/opc/pom.xml b/opc/target/classes/META-INF/maven/com.back/opc/pom.xml new file mode 100644 index 0000000..cd0d315 --- /dev/null +++ b/opc/target/classes/META-INF/maven/com.back/opc/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + opc + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..9b6ba3e --- /dev/null +++ b/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + com.back + processor + 0.0.1-SNAPSHOT + pom + processor + processor + + common + selfDevelop + opc + carCheck + carCheckNew + + \ No newline at end of file diff --git a/selfDevelop/conn.properties b/selfDevelop/conn.properties new file mode 100644 index 0000000..7f742c7 --- /dev/null +++ b/selfDevelop/conn.properties @@ -0,0 +1,17 @@ +driver = com.mysql.jdbc.Driver +url = jdbc:mysql://8.129.11.230:3306/samr?connectTimeout=10000&socketTimeout=60000 +user = root +pwd = samr2020 +language = en + +opcControl = false +MControlTiming15 = false +MControlTiming60 = false + +ForWard485 = false +LampTiming = false +LampDay3761Timing =false +TerminalDay3761Timing =false +AnalysisOfTunnelElectricity=false + +gprsIp=172.26.187.230 \ No newline at end of file diff --git a/selfDevelop/pom.xml b/selfDevelop/pom.xml new file mode 100644 index 0000000..1491b61 --- /dev/null +++ b/selfDevelop/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + selfDevelop + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + + \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/action/Work.java b/selfDevelop/src/main/java/com/back/action/Work.java new file mode 100644 index 0000000..ad733cf --- /dev/null +++ b/selfDevelop/src/main/java/com/back/action/Work.java @@ -0,0 +1,3410 @@ +package com.back.action; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.net.Socket; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; + +import org.apache.commons.lang3.StringUtils; + +import com.back.common.Common; +import com.back.common.MeterTimingParams; +import com.back.common.RunParams; +import com.back.communication.SerialComm; +import com.back.communication.SerialComm485; +import com.back.communication.SocketComm; +import com.back.jdbc.SQLHelper; + +import com.back.entity.Control; +import com.back.entity.Mcontrol; +import com.back.entity.Sensor; +import com.back.entity.SyncEntity; +import com.back.protocol.GW3761; +import com.back.protocol.Lon16; +import com.back.protocol.Protocol; +import com.back.protocol.SystemParameter; +import com.back.sync.DataInstance; +import com.back.sync.DataSyncUtil; +import com.back.threadpool.ThreadPool; + + + +public class Work { + + // private static LampOld lampold = new LampOld(); //旧集中器解码类 + private static GW3761 gw3761 = new GW3761(); // 新集中器解码类 + private static Lon16 lon16 = new Lon16(); + + private static ThreadPool threadPool; + + private static SerialComm serial; + private static SerialComm485 serial485; + + private static String gprsIp; // 国网专用 + private static int gprsPort; + + private static String gprsIpLon; // LON16 + private static int gprsPortLon; + + private static int reSend; + private static int gprsTimeOut;// GPRS超时时间 + private static int comTimeOut;// 串口超时时间 + private static int timeDiscard;// 超时不处理时间(秒) + private static int threadsize; + private static String terminalCom;// 集中器连接串口 + + private static String terminalCom485;// 485总线通信口 例: COM + private static int beat485;// 485集中器跳时间 (毫秒) + private static int comTimeOut485;// 集中器连接串口(毫秒) + + private static int PFC = 0; // 启动帧帧序号计数器(0~255) + + private static int lampcounted = 0;// 已运行次数 + private static String lampnextrunttime;// 下次运行时间 + + private static int newcounted = 0;// 已运行次数 + private static String newnextruntime;// 下次运行时间 + + private static int density = 1;// 曲线类数据抄读冻结密度[系统编码表] + private static int unitminute = 15;// 单位分钟 + + private static String powerrunHour = "";// 电表日冻结数据抄读时间(整点) 格式:HH[系统编码表] + private static String readedday = "";// 电表日冻结数据最新抄读日 + private static int powercount = 8;// 电表抄读补抄次数[系统编码表] + + private static Long luxChangeLimit = (long) 100;// 光感控制-照度变化阀值 + + private static int deleteruncount = 0; // 执行操作操作的记数器 + private static int deleterunmax = 20; // 删除周期 + + public static String language = ""; // 语言 + + public static boolean timer_redo_run = false; + + public static RunParams runParams; + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public Work() { + SystemParameter.GetPostParams(); + runParams = SystemParameter.runParams; + // 转发参数设置 + gprsIp = SystemParameter.runParams.gprsIp; + gprsPort = SystemParameter.runParams.gprsPort; + + gprsIpLon = SystemParameter.runParams.gprsIpLon; + gprsPortLon = SystemParameter.runParams.gprsPortLon; + + reSend = SystemParameter.runParams.reSend; + gprsTimeOut = SystemParameter.runParams.gprsTimeOut; + comTimeOut = SystemParameter.runParams.comTimeOut; + timeDiscard = SystemParameter.runParams.timeDiscard; + threadsize = SystemParameter.runParams.threadsize; + terminalCom = SystemParameter.runParams.terminalCom; + + terminalCom485 = SystemParameter.runParams.terminalCom485; + beat485 = SystemParameter.runParams.beat485; + comTimeOut485 = SystemParameter.runParams.comTimeOut485; + + serial = SerialComm.getInstance(terminalCom); + serial485 = SerialComm485.getInstance(terminalCom485); + SerialComm485.beat485 = beat485; + SerialComm485.comTimeOut485 = comTimeOut485; + + language = SystemParameter.runParams.language; + + threadPool = ThreadPool.getInstance(threadsize, language);// 创建线程池 + + try { + Thread.sleep(500);// 休眠500毫秒,以便让线程池中的工作线程全部运行 + } catch (InterruptedException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /* + * 转发485命令 隧道项目中,专用485总线通信方式 + */ + public void ForWard485() { + Reconnect(); + + int cmdid; + String terminal; + String cmdcode; + String ruletype; + String responsetype; + + // 要发送指令数据查询 + String strsql = "SELECT top 10 CommandID,terminal,cmdcode,comtype,ruletype,responsetype,WTime FROM commands "; + strsql += "WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<" + timeDiscard + + " and Status=0 and comtype='0003'";// 0001 网口 0002 GPRS 0003 + // RS485 0004 NB通道 + // 0005串口 + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int i = 0; + try { + while (rSet.next()) { + + cmdid = rSet.getInt("CommandID"); + terminal = rSet.getString("terminal"); + cmdcode = rSet.getString("cmdcode"); + ruletype = rSet.getString("ruletype"); + responsetype = rSet.getString("responsetype"); + + /* + * serial.init(); if (ruletype.equals("0001")) { + * serial.start(0); // Lon16 } else { serial.start(2);// 376.1 } + * if (serial.isStart) { serial.writeComm(cmdid, terminal, + * cmdcode, ruletype, "", 0, comTimeOut, "", responsetype, ""); + * } + */ + serial485.addTask(cmdid, terminal, cmdcode, ruletype, "", 0, comTimeOut, "", responsetype, ""); + + // 添加到485通信命令队列中。 + Protocol.updateCommands(terminal, cmdid); // 更新指令表读取标识 + i++; + if (i > 5000) { + i = 0; + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "-> Run!"); + } + } + } catch (Exception e) { + if (serial.isOpen) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Send ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Close ERROR:" + e.getMessage()); + } + } + + /** 串口转发指令操作 */ + public void ForWardPort() { + Reconnect(); + + int cmdid; + String terminal; + String cmdcode; + String ruletype; + String responsetype; + + // 要发送指令数据查询 + String strsql = "SELECT top 10 CommandID,terminal,cmdcode,comtype,ruletype,responsetype FROM commands "; + strsql += "WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<" + timeDiscard + + " and Status=0 and comtype='0005'";// 0001 网口 0002 GPRS + // 0003 RS485 0004 + // NB通道 0005串口 + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int i = 0; + try { + while (rSet.next()) { + System.out.println("ForWardPort!"); + cmdid = rSet.getInt("CommandID"); + terminal = rSet.getString("terminal"); + cmdcode = rSet.getString("cmdcode"); + ruletype = rSet.getString("ruletype"); + responsetype = rSet.getString("responsetype"); + + serial.init(); + if (ruletype.equals("0001")) { + serial.start(0); // Lon16 + } else { + serial.start(2);// 376.1 + } + if (serial.isStart) { + serial.writeComm(cmdid, terminal, cmdcode, ruletype, "", 0, comTimeOut, "", responsetype, ""); + } + Protocol.updateCommands(terminal, cmdid); // 更新指令表读取标识 + i++; + if (i > 5000) { + i = 0; + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "-> Run!"); + } + } + } catch (Exception e) { + if (serial.isOpen) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Send ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Close ERROR:" + e.getMessage()); + } + } + + /* + * 功能:隧道光感处理 tunnel + */ + public void ForWardTunnel() { + Reconnect(); + int i = 0; + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + String strsql = "SELECT top " + threadsize + + " lightsensordata.id id,terminalM,terminalC,scene,wtime,comtype FROM lightsensordata,lightsensorcontrol "; + strsql += " WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<60 AND lightsensordata.terminal = lightsensorcontrol.terminalM " + + " and ReadStatus=0 "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + int lastSceneId = 0; + String terminal = ""; + while (rSet.next()) { + + int sceneId = rSet.getInt("id"); + String terminalM = rSet.getString("terminalM"); + String terminalC = rSet.getString("terminalC"); + String scene = Integer.toHexString(rSet.getInt("scene")); + String wtime = rSet.getString("wtime"); + String responsetype = "0"; + String ruletype = "0002"; + String comtype = rSet.getString("comtype");// 0001 com 0002 + // GPRS + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminalM + + " " + terminalC + "] "); + + if (scene.length() == 1) + scene = "0" + scene; + // 获取命令 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0110" + binarypfc); + char[] chars = terminalC.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + String cmdcode = "0000080310" + "01" + scene + "02" + scene + "03" + scene + "04" + scene + "05" + + scene + "06" + scene + "07" + scene + "08" + scene + "09" + scene + "0A" + scene + "0B" + + scene + "0C" + scene + "0D" + scene + "0E" + scene + "0F" + scene + "10" + scene; + // +"11" + scene + // +"12" + scene; + + cmdcode = gw3761.create3761("6B", adomain, "A5", seqdomain, cmdcode); + + if (comtype.equals("0002")) { + addTask(ruletype, terminalC, cmdcode, sceneId, "", 0, wtime, "", responsetype, ""); + } else { // 串口 + Protocol.wCommands(terminalC, cmdcode, comtype, "0002"); + } + + if (lastSceneId != sceneId) { + if (lastSceneId != 0) + Protocol.updateLightSensor(terminal, lastSceneId); + lastSceneId = sceneId; + terminal = terminalM; + } + } + if (lastSceneId != 0) + Protocol.updateLightSensor(terminal, lastSceneId); // 更新光感数据读取标识 + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: "); + } + } + + /* + * 功能:隧道光感处理 tunnel + */ + public void ForWardTunnelLight() { + Reconnect(); + int i = 0; + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + String strsql = "SELECT top " + threadsize + + " lightsensordata1.id id,terminalM,terminalC,traffics,wtime,(SELECT terminals.ComModel FROM terminals WHERE terminals.comid=lightsensorcontrol.terminalC) comtype FROM lightsensordata1,lightsensorcontrol "; + strsql += " WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<60 AND lightsensordata1.terminal = lightsensorcontrol.terminalM " + + " and ReadStatus=0 "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + int lastSceneId = 0; + String terminal = ""; + while (rSet.next()) { + + int sceneId = rSet.getInt("id"); + String terminalM = rSet.getString("terminalM"); + String terminalC = rSet.getString("terminalC"); + String traffics = Long.toHexString(rSet.getLong("traffics")); + String wtime = rSet.getString("wtime"); + String responsetype = "0"; + String ruletype = "0002"; + String comtype = rSet.getString("comtype");// 0001 com 0002 + // GPRS + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminalM + + " " + terminalC + "] "); + + while (traffics.length() < 8) + traffics = "0" + traffics; + + // 获取命令 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0110" + binarypfc); + char[] chars = terminalC.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + String cmdcode = "00008003" + traffics.substring(6, 8) + traffics.substring(4, 6) + + traffics.substring(2, 4) + traffics.substring(0, 2); + // +"11" + scene + // +"12" + scene; + + cmdcode = gw3761.create3761("6B", adomain, "A5", seqdomain, cmdcode); + + if (comtype.equals("0002")) { + addTask(ruletype, terminalC, cmdcode, sceneId, "", 0, wtime, "", responsetype, ""); + } else { // 串口 + Protocol.wCommands(terminalC, cmdcode, comtype, "0002"); + } + + if (lastSceneId != sceneId) { + if (lastSceneId != 0) + Protocol.updateLightSensor(terminal, lastSceneId); + lastSceneId = sceneId; + terminal = terminalM; + } + } + if (lastSceneId != 0) + Protocol.updateLightSensor(terminal, lastSceneId); // 更新光感数据读取标识 + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: "); + } + } + + /** + * 获取 + * + * @param sql + * @return + */ + private long getLondDdatabysql(String sql) { + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(sql); + long lux = 0; + try { + while (rSet.next()) { + lux = rSet.getLong(1); + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + return lux; + } + + /** + * 获取 + * + * @param sql + * @return + */ + private int getIntDatabysql(String sql) { + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(sql); + int lux = 0; + try { + while (rSet.next()) { + lux = rSet.getInt(1); + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + return lux; + } + + /** + * 功能:处理传感器失效时,处理 + */ + private void ForWardTunnelControl_Time() { + String strsql = "select DISTINCT(terminalC) FROM lightsensorcontrol "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + // 没有设置记录 + return; + } + try { + String[] DimmingStr = new String[16]; + int Dimming = 0; + String nowtime = Common.getDateStr4(); + String wtime = Common.getDateStr0(); + String sqlString = "select dimming1,dimming2,dimming3,dimming4,dimming5,dimming6,dimming7,dimming8,dimming9,dimming10,dimming11,dimming12,dimming13,dimming14,dimming15,dimming16 from "; + while (rSet.next()) { + String terminalC = rSet.getString("terminalC"); + sqlString = sqlString + " timeControls where terminal='" + terminalC + "' and minTime<='" + nowtime + + "' and '" + nowtime + "'<=maxTime"; + + Statement stmt1 = null; + int j; + for (j = 0; j < 16; j++) + DimmingStr[j] = "64"; + + ResultSet rSet1 = SQLHelper.getResultSet(sqlString); + try { + while (rSet1.next()) { // 获取调光值 + for (j = 0; j < 16; j++) { + Dimming = rSet1.getInt(j + 1); + if (Dimming < 10) + Dimming = 10; + if (Dimming > 100) + Dimming = 100; + DimmingStr[j] = Integer.toHexString(Dimming); + if (DimmingStr[j].length() == 1) + DimmingStr[j] = "0" + DimmingStr[j]; + } + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->时序控制!"); + String responsetype = "0"; + String ruletype = "0002"; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminalC + "] "); + + // 获取命令 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0110" + binarypfc); + char[] chars = terminalC.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + String cmdcode = "0000020306" + "01" + DimmingStr[0] + "02" + DimmingStr[0] + "03" + + DimmingStr[2] + "04" + DimmingStr[3] + "05" + DimmingStr[4] + "06" + DimmingStr[5] + + "07" + DimmingStr[6] + "08" + DimmingStr[7] + "09" + DimmingStr[8] + "0A" + + DimmingStr[9] + "0B" + DimmingStr[10] + "0C" + DimmingStr[11] + "0D" + DimmingStr[12] + + "0E" + DimmingStr[13] + "0F" + DimmingStr[14] + "10" + DimmingStr[15]; + // +"11" + scene + // +"12" + scene; + // System.out.println("照度:" + lux[0] + " " + lux[1] + + // " " + lux[2] + " " + lux[3] + " " + // + lux[4] + " " + lux[5]); + + cmdcode = gw3761.create3761("6B", adomain, "A5", seqdomain, cmdcode); + + addTask(ruletype, terminalC, cmdcode, 0, "", 0, wtime, "", responsetype, ""); + } // while (rSet1.next()) + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + continue; + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e1) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e1.getMessage()); + } + + } + + } catch (Exception e) { + + } + } + + public Date lastTimeDate = null; + + /* + * 功能:光控控制处理 ForWardOPCControl + */ + public void ForWardOPCControl() { + Reconnect(); + int i = 0; + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + String strsql = "SELECT top " + threadsize + + " lightsensordata1.id id,terminalM,terminalC,traffics,lightsensordata1.lux lux,terminal,wtime,terminals.ComModel comtype,terminals.lux lastlux,luxstate FROM " + + "lightsensordata1,lightsensorcontrol,terminals "; + strsql += " WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<60 AND lightsensordata1.terminal = lightsensorcontrol.terminalM AND terminals.comid=lightsensorcontrol.terminalC " + + " and ReadStatus=0 and terminals.sensor='1' "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int rowCount = 0; + try { + + int lastSceneId = 0; + int sceneId = -1; + String terminal = ""; + + String trafficsStr; + String luxStr; + + while (rSet.next()) { + rowCount++; + lastTimeDate = new Date(); + + sceneId = rSet.getInt("id"); + // trafficsStr = rSet.getString("traffics"); + luxStr = rSet.getString("lux"); + terminal = rSet.getString("terminal"); + String terminalM = rSet.getString("terminalM"); + String terminalC = rSet.getString("terminalC"); + // String wtime = rSet.getString("wtime"); + String comtype = rSet.getString("comtype");// 0001 com 0002 + // GPRS + String responsetype = "0"; + String ruletype = "0002"; + + String luxstateStr = rSet.getString("luxstate"); + String lastluxStr = rSet.getString("lastlux"); + + Boolean NoSend = false; + try { + long lastluxL = Long.valueOf(lastluxStr); + long luxL = Long.valueOf(luxStr); + + // 2018 04 21 上一次命令下发成功 且 照度变化没有超过阀值时 不进行处理 + if (Math.abs(lastluxL - luxL) < luxChangeLimit && luxstateStr.equals("1")) { + NoSend = true; + ; + } + + // 更新集中器 状态 + else { + String strsql1 = "update terminals set lux=" + luxStr + ",luxstate=0,luxTime='" + + Common.getYesterdayStr0() + "' where comid='" + terminalC + "'"; + SQLHelper.ExecSql(strsql1); + } + + } catch (Exception e) { + + } + + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminalM + + " " + terminalC + "] "); + + // 获取命令 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0110" + binarypfc); + char[] chars = terminalC.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + String str = Common.dec2Hex(Long.valueOf(luxStr), 8); + String cmdcode = "00000204" + str.substring(6, 8) + str.substring(4, 6) + str.substring(2, 4) + + str.substring(0, 2); + + cmdcode = gw3761.create3761("6B", adomain, "A5", seqdomain, cmdcode); + + if (NoSend == false) { + if (comtype.equals("0002")) { + addTask(ruletype, terminalC, cmdcode, 0, "", 0, Common.getDateStr0(), "", responsetype, ""); + } else { // 串口 + Protocol.wCommands(terminalC, cmdcode, comtype, "0002"); + } + } + + if (lastSceneId != sceneId) { + if (lastSceneId != 0) + Protocol.updateLightSensorAndTraffics(terminal, lastSceneId, "100"); + lastSceneId = sceneId; + terminal = terminalM; + } + } + if (lastSceneId != 0) + Protocol.updateLightSensorAndTraffics(terminal, lastSceneId, "100"); // 更新光感数据读取标识 + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + + // 处理传感器有问题时 + if (rowCount == 0) { + if (lastTimeDate == null) + lastTimeDate = new Date(); + if ((((new Date().getTime() - lastTimeDate.getTime()) / 60000) > 2)) {// 超过两分钟传感器没有反应 + ForWardTunnelControl_Time(); + lastTimeDate = new Date(); + } + } + } else { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: thread size "); + } + } + + /* + * 功能:隧道控制处理 tunnel + */ + public void ForWardTunnelControl() { + Reconnect(); + int i = 0; + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + String strsql = "SELECT top " + threadsize + + " lightsensordata1.id id,terminalM,terminalC,traffics,lux,terminal,wtime,comtype FROM lightsensordata1,lightsensorcontrol "; + strsql += " WHERE datediff(s,WTime,CONVERT(varchar(100), GETDATE(), 120))<60 AND lightsensordata1.terminal = lightsensorcontrol.terminalM " + + " and ReadStatus=0 "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int rowCount = 0; + try { + + int lastSceneId = 0; + int sceneId = -1; + String terminal = ""; + String nowtime = Common.getDateStr4(); + long[] lux = new long[6]; + int[] Dimming = new int[6]; + String[] DimmingStr = new String[16]; + String[] DimmingDecStr = new String[16];// --10进制字符串 + long tempLux = 0; + long tempLux1 = 0; + + String trafficsStr; + String luxStr; + + while (rSet.next()) { + rowCount++; + lastTimeDate = new Date(); + + sceneId = rSet.getInt("id"); + trafficsStr = rSet.getString("traffics"); + luxStr = rSet.getString("lux"); + terminal = rSet.getString("terminal"); + String terminalM = rSet.getString("terminalM"); + String terminalC = rSet.getString("terminalC"); + String wtime = rSet.getString("wtime"); + String comtype = rSet.getString("comtype");// 0001 com 0002 + // GPRS + // if (lastSceneId != sceneId) + { + /* + * // 计算中间段 // 获取车流量时照度 tempLux = getLondDdatabysql( + * "select lux from tunneltraffics where minTraffics<=" + * + trafficsStr + " and " + trafficsStr + + * "<=maxTraffics and comid='" + terminal + + * "' and datatype='0002'"); + * + * // 获取时间照度 tempLux1 = getLondDdatabysql( + * "select lux from tunneltimes where minTime<='" + + * nowtime + "' and '" + nowtime + + * "'<=maxTime and comid='" + terminal + + * "' and datatype='0002'"); + * + * tempLux = tempLux + tempLux1; if (tempLux < 0) + * tempLux = 200; lux[4] = tempLux; + * + * // 计算出口段 lux[5] = lux[4] * 2; + * + * // 计算加强段 // 通过洞外照度获取洞内照度 tempLux = getLondDdatabysql( + * "select lux from tunnelilluminances where minlux<=" + + * luxStr + " and " + luxStr + "<=maxlux and comid='" + + * terminal + "' and datatype='0001'"); // 获取时间照度 + * tempLux1 = getLondDdatabysql( + * "select lux from tunneltimes where minTime<='" + + * nowtime + "' and '" + nowtime + + * "'<=maxTime and comid='" + terminal + + * "' and datatype='0001'"); tempLux = tempLux + + * tempLux1; // 获取车流量时照度 tempLux1 = getLondDdatabysql( + * "select lux from tunneltraffics where minTraffics<=" + * + trafficsStr + " and " + trafficsStr + + * "<=maxTraffics and comid='" + terminal + + * "' and datatype='0001'"); tempLux = tempLux + + * tempLux1; if (tempLux < 0) tempLux = 200; lux[0] = + * tempLux; + * + * // 计算过渡段 tempLux1 = lux[4]; tempLux = tempLux - + * tempLux1; tempLux = tempLux / 4; for (int j = 1; j < + * 4; j++) lux[j] = lux[j - 1] - tempLux; + * + * // 获取转换后的调光值 for (int j = 0; j < 6; j++) { Dimming[j] + * = getIntDatabysql( + * "select Dimming from IlluminanceConvertDimmings where comid='" + * + terminal + "' and GroupID=" + String.valueOf(j + 1) + * + " and minlux<=" + String.valueOf(lux[j]) + + * " and " + String.valueOf(lux[j]) + "<=maxlux"); if + * (Dimming[j] < 10) Dimming[j] = 10; if (Dimming[j] > + * 100) Dimming[j] = 100; + * + * DimmingStr[j] = Integer.toHexString(Dimming[j]); if + * (DimmingStr[j].length() == 1) DimmingStr[j] = "0" + + * DimmingStr[j]; } } + */ + String sqlString = "select dimming1,dimming2,dimming3,dimming4,dimming5,dimming6,dimming7,dimming8,dimming9,dimming10,dimming11,dimming12,dimming13,dimming14,dimming15,dimming16 from "; + tempLux = Long.valueOf(trafficsStr); + tempLux1 = Long.valueOf(luxStr); + if ((tempLux < 5.8 || tempLux > 20) && tempLux > 0) // 小于350 + { // 车流量 + sqlString = sqlString + " tunnelControls where terminal='" + terminalC + + "' and minTraffics<=" + trafficsStr + " and " + trafficsStr + "<=maxTraffics"; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->车流量策略!"); + } else if (tempLux1 == 0) // 时序控制 + { + sqlString = sqlString + " timeControls where terminal='" + terminalC + "' and minTime<='" + + nowtime + "' and '" + nowtime + "'<=maxTime"; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->时序控制!"); + } else // 光照度感 + { + sqlString = sqlString + " illuminanceControls where terminal='" + terminalC + + "' and minlux<=" + luxStr + " and " + luxStr + "<=maxlux"; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->光照度感策略!"); + } + + Statement stmt1 = null; + int j; + for (j = 0; j < 16; j++) { + DimmingStr[j] = "64"; + DimmingDecStr[j] = "100"; + } + ResultSet rSet1 = SQLHelper.getResultSet(sqlString); + try { + while (rSet1.next()) { + for (j = 0; j < 16; j++) { + Dimming[0] = rSet1.getInt(j + 1); + if (Dimming[0] < 10) + Dimming[0] = 10; + if (Dimming[0] > 100) + Dimming[0] = 100; + DimmingStr[j] = Integer.toHexString(Dimming[0]); + DimmingDecStr[j] = Integer.toString(Dimming[0]); + if (DimmingStr[j].length() == 1) + DimmingStr[j] = "0" + DimmingStr[j]; + } + + } + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.getMessage()); + + continue; + } + try { + stmt1 = rSet1.getStatement(); + rSet1.close(); + stmt1.close(); + rSet1 = null; + stmt1 = null; + } catch (Exception e1) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "1->ERROR:" + e1.getMessage()); + } + + String responsetype = "0"; + String ruletype = "0002"; + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + + terminalM + " " + terminalC + "] "); + + // 获取命令 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0110" + binarypfc); + char[] chars = terminalC.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + String cmdcode = "0000020306" + "01" + DimmingStr[0] + "02" + DimmingStr[1] + "03" + + DimmingStr[2] + "04" + DimmingStr[3] + "05" + DimmingStr[4] + "06" + DimmingStr[5] + + "07" + DimmingStr[6] + "08" + DimmingStr[7] + "09" + DimmingStr[8] + "0A" + + DimmingStr[9] + "0B" + DimmingStr[10] + "0C" + DimmingStr[11] + "0D" + DimmingStr[12] + + "0E" + DimmingStr[13] + "0F" + DimmingStr[14] + "10" + DimmingStr[15]; + // +"11" + scene + // +"12" + scene; + // System.out.println("照度:" + lux[0] + " " + lux[1] + + // " " + lux[2] + " " + lux[3] + " " + // + lux[4] + " " + lux[5]); + + cmdcode = gw3761.create3761("6B", adomain, "A5", seqdomain, cmdcode); + // 打印下发的调光值 + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->下发调光值:" + + DimmingDecStr[0]); + + if (comtype.equals("0002")) { + addTask(ruletype, terminalC, cmdcode, 0, "", 0, Common.getDateStr0(), "", responsetype, ""); + } else { // 串口 + Protocol.wCommands(terminalC, cmdcode, comtype, "0002"); + } + + if (lastSceneId != sceneId) { + if (lastSceneId != 0) + Protocol.updateLightSensorAndTraffics(terminal, lastSceneId, DimmingDecStr[0]);// --zhangshengbao + lastSceneId = sceneId; + terminal = terminalM; + } + } + } + if (lastSceneId != 0) + Protocol.updateLightSensorAndTraffics(terminal, lastSceneId, DimmingDecStr[0]); // 更新光感数据读取标识 + // --zhangshengbao + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + + // 处理传感器有问题时 + if (rowCount == 0) { + if (lastTimeDate == null) + lastTimeDate = new Date(); + if ((((new Date().getTime() - lastTimeDate.getTime()) / 60000) > 2)) {// 超过两分钟传感器没有反应 + ForWardTunnelControl_Time(); + lastTimeDate = new Date(); + } + } + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: "); + } + } + + /** GPRS转发指令 操作 */ + public void ForWardGprs() { + Reconnect(); + int i = 0; + + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + + // System.out.println("\nGPRS转发指令:"); + String strsql = "SELECT CommandID,terminal,cmdcode,comtype,ruletype,wtime,responsetype FROM commands "; + + // 0001 网口、 0002 GPRS、 0003 RS485、 0004 NB通道、 0005 串口 + strsql += " WHERE TIMESTAMPDIFF(SECOND, WTime, NOW())<" + timeDiscard + + " and Status=0 and (comtype='0002' or comtype='0001') LIMIT " + threadsize; + + Statement stmt = null; + ResultSet rSet = SQLHelper.ExecProcwCommands(strsql); + if (rSet == null) { + return; + } + + try { + //System.out.println("查询记录:"+rSet.getRow()); + while (rSet.next()) { + + int cmdid = rSet.getInt("CommandID"); + String terminal = rSet.getString("terminal"); + String cmdcode = rSet.getString("cmdcode"); + String ruletype = rSet.getString("ruletype"); + String wtime = rSet.getString("wtime"); + String responsetype = rSet.getString("responsetype"); + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "[" + terminal + "] "); + Protocol.updateCommands(terminal, cmdid); // 更新指令表读取标识 + + boolean send = true; + String syncSql = "SELECT datasynciseffect FROM DataSync d LEFT JOIN terminals t " + + "ON d.terminalid = t.id WHERE t.comid = " + terminal; + try { + ResultSet resultSet = SQLHelper.getResultSet(syncSql); + while (resultSet.next()) { + int data = resultSet.getInt("datasynciseffect"); + if (data == 1) { + String remark = "Sync Busy"; + SQLHelper.ExecProcwreceivedata(cmdid, terminal, null, 5, remark); + send = false; + } + } + } catch (SQLException e) { + Log.writelog1("Sql 查询出错,syncSql: " + syncSql); + e.printStackTrace(); + } + + // socket 发送命令 + if (send) { + addTask(ruletype, terminal, cmdcode, cmdid, "", 0, wtime, "", responsetype, ""); + } + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "1->ERROR:" + e.getMessage()); + } + } else { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2: "); + } + } + + ExecutorService executorService = Executors.newFixedThreadPool(1); + + public void DataSync() { + Reconnect(); + int i = 0; + + if (threadPool.GetWorkSize() > threadsize * 2 == false) { + // 1. 查询 待同步 配电箱数据 + String syncSql = " SELECT t.comid terminal, d.controlsiseffect, d.mcontrolsiseffect, " + + " d.carsensorsiseffect, d.luminancesensorsiseffect, d.illuminationsensorsisEffect " + + " FROM datasync d LEFT JOIN terminals t ON d.terminalid = t.id " + + " WHERE d.datasynciseffect = 1 "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(syncSql); + if (rSet == null) { + return; + } + + try { + List entityList = new ArrayList<>(); + while (rSet.next()) { + SyncEntity entity = new SyncEntity(); + entity.setTerminal(rSet.getString("terminal")); + entity.setControlsiseffect(rSet.getInt("controlsiseffect")); + entity.setMcontrolsiseffect(rSet.getInt("mcontrolsiseffect")); + entity.setIlluminationsensorsisEffect(rSet.getInt("illuminationsensorsisEffect")); + entity.setLuminancesensorsiseffect(rSet.getInt("luminancesensorsiseffect")); + entity.setCarsensorsiseffect(rSet.getInt("carsensorsiseffect")); + entityList.add(entity); + } + + if (entityList.isEmpty()) { + return; + } + + for (int m = 0; m < entityList.size(); m++) { + SyncEntity syncEntity = entityList.get(m); + String nowTerminalId = syncEntity.getTerminal(); + + // 查询所有设备数据 + DataInstance dataInstance = DataInstance.getInstance(); + initData(syncEntity, dataInstance); + + // 预发送 + String message = DataSyncUtil.preSendCmd(nowTerminalId); + Log.writelog1("\n\n 预发送命令,message: " + message); + FutureTask futureTask = new FutureTask(new syncTask(message)); + executorService.execute(futureTask); + Integer preResult = futureTask.get(); + dataInstance.setState(preResult); + + String preUpdateSql = " UPDATE datasync d LEFT JOIN terminals t ON d.terminalid = t.id " + + " SET d.datasynciseffect = 1, d.handiseffect = 0, progress = 0 " + " WHERE t.comid = " + + nowTerminalId; + SQLHelper.ExecSql(preUpdateSql); + + if (preResult == 0) { + + // 灯杆同步 + List controlList = dataInstance.getControlList(); + if (!controlList.isEmpty()) { + controlSync(nowTerminalId, controlList, dataInstance); + } + + // 回路同步 + List mcontrolList = dataInstance.getMcontrolList(); + if (!mcontrolList.isEmpty()) { + mcontrolSync(nowTerminalId, mcontrolList, dataInstance); + } + + // 照度传感器同步 + List illumList = dataInstance.getIllumList(); + if (!illumList.isEmpty()) { + sensorSync(nowTerminalId, illumList, "03", dataInstance); + } + + // 亮度传感器同步 + List lumList = dataInstance.getLumList(); + if (!lumList.isEmpty()) { + sensorSync(nowTerminalId, lumList, "04", dataInstance); + } + + // 车流量传感器同步 + List carsenList = dataInstance.getCarsenList(); + if (!carsenList.isEmpty()) { + sensorSync(nowTerminalId, carsenList, "05", dataInstance); + } + + } + + int state = dataInstance.getState(); + int value = 0; + switch (state) { + case 0: { + value = 0; + break; + } + default: + value = 2; + break; + } + + // 5. 根据 配电箱ID 更新同步表数据 + String updateSql = " UPDATE datasync d LEFT JOIN terminals t ON d.terminalid = t.id " + + " SET d.datasynciseffect = %s, d.handiseffect = 0 " + " WHERE t.comid = " + nowTerminalId; + SQLHelper.ExecSql(String.format(updateSql, value)); + + DataInstance.resetInstance(); + Log.writelog1("\r\n 设备数据同步完成"); + + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + } + + public void initData(SyncEntity syncEntity, DataInstance dataInstance) throws SQLException { + + String nowTerminalId = syncEntity.getTerminal(); + + List controlList = new ArrayList(); + if (syncEntity.getControlsiseffect() == 1) { + String controlSql = " SELECT id, comid, num, GroupID, worktype, tunnel, type, protocol " + + " FROM controls WHERE terminal = '" + nowTerminalId + "'"; + ResultSet controlSet = SQLHelper.getResultSet(controlSql); + while (controlSet.next()) { + Control control = new Control(); + control.setId(controlSet.getInt("id")); + control.setComid(controlSet.getString("comid")); + control.setNum(controlSet.getInt("num")); + control.setGroupid(controlSet.getInt("GroupID")); + control.setWorktype(controlSet.getString("worktype")); + control.setTunnel(controlSet.getString("tunnel")); + control.setType(controlSet.getString("type")); + control.setProtocol(controlSet.getString("protocol")); + controlList.add(control); + } + dataInstance.setControlList(controlList); + } + + List mcontrolList = new ArrayList(); + if (syncEntity.getMcontrolsiseffect() == 1) { + String mcontrolSql = " SELECT id, comid, num, groups, worktype, tunnel, type, protocol, ratio " + + " FROM mcontrols WHERE terminal = '" + nowTerminalId + "'"; + ResultSet mcontrolSet = SQLHelper.getResultSet(mcontrolSql); + while (mcontrolSet.next()) { + Mcontrol mcontrol = new Mcontrol(); + mcontrol.setId(mcontrolSet.getInt("id")); + mcontrol.setComid(mcontrolSet.getString("comid")); + mcontrol.setNum(mcontrolSet.getInt("num")); + mcontrol.setGroups(mcontrolSet.getString("groups")); + mcontrol.setWorktype(mcontrolSet.getString("worktype")); + mcontrol.setTunnel(mcontrolSet.getString("tunnel")); + mcontrol.setType(mcontrolSet.getString("type")); + mcontrol.setProtocol(mcontrolSet.getString("protocol")); + mcontrol.setRatio(mcontrolSet.getInt("ratio")); + mcontrolList.add(mcontrol); + } + dataInstance.setMcontrolList(mcontrolList); + } + + // 照度 + List illumList = new ArrayList(); + // 亮度 + List lumList = new ArrayList(); + // 车流量 + List carsenList = new ArrayList(); + + String sensorSql = " SELECT id, comid, num, worktype, tunnel, type, protocol, ratio, cycle, lane " + + " FROM sensors WHERE terminal = '" + nowTerminalId + "'"; + ResultSet sensorSet = SQLHelper.getResultSet(sensorSql); + while (sensorSet.next()) { + Sensor sensor = new Sensor(); + sensor.setId(sensorSet.getInt("id")); + sensor.setComid(sensorSet.getString("comid")); + sensor.setNum(sensorSet.getInt("num")); + sensor.setWorktype(sensorSet.getString("worktype")); + sensor.setTunnel(sensorSet.getString("tunnel")); + String type = sensorSet.getString("type"); + sensor.setType(type); + sensor.setProtocol(sensorSet.getString("protocol")); + sensor.setRatio(sensorSet.getInt("ratio")); + sensor.setCycle(sensorSet.getInt("cycle")); + sensor.setLane(sensorSet.getInt("lane")); + + if (syncEntity.getIlluminationsensorsisEffect() == 1 && type.equals("0001")) { + illumList.add(sensor); + } else if (syncEntity.getLuminancesensorsiseffect() == 1 && type.equals("0002")) { + lumList.add(sensor); + } else if (syncEntity.getCarsensorsiseffect() == 1 && type.equals("0003")) { + carsenList.add(sensor); + } + } + dataInstance.setIllumList(illumList); + dataInstance.setLumList(lumList); + dataInstance.setCarsenList(carsenList); + int totalCount = controlList.size() + mcontrolList.size() + illumList.size() + lumList.size() + + carsenList.size(); + dataInstance.setTotalCount(totalCount); + } + + public void sensorSync(String nowTerminalId, List sensorList, String sensorType, DataInstance dataInstance) + throws InterruptedException, ExecutionException { + + String sensorName = ""; + switch (sensorType) { + case "03": { + sensorName = "照度传感器"; + break; + } + case "04": { + sensorName = "亮度传感器"; + break; + } + case "05": { + sensorName = "车流量传感器"; + break; + } + default: + break; + } + + int state = dataInstance.getState(); + + List idList = new ArrayList<>(); + List sendList = new ArrayList(); + for (int i = 0; i < sensorList.size(); i++) { + sendList.add(sensorList.get(i)); + idList.add(sensorList.get(i).getId()); + + if (state == 0 && sendList.size() == 50) { + // 4.2 数据发送 + String message = DataSyncUtil.generateSensorData(nowTerminalId, sendList, 0, sensorType); + // addTask("", nowTerminalId, message, 0, "", 0, "", "", "", + // ""); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + + sensorName + "发送结果,message:" + message); + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + state = result; + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update sensors set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + + sendList.clear(); + idList.clear(); + } + } + + if (state == 0 && !sendList.isEmpty()) { + // 4.2 数据发送 + String message = DataSyncUtil.generateSensorData(nowTerminalId, sendList, 0, sensorType); + // addTask("", nowTerminalId, message, 0, "", 0, "", "", "", ""); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + sensorName + + "发送结果,message:" + message); + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update sensors set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + } + } + + public void mcontrolSync(String nowTerminalId, List mcontrolList, DataInstance dataInstance) + throws InterruptedException, ExecutionException { + + int state = dataInstance.getState(); + + // 3.1 根据 配电箱ID 查询 待发送 回路数据 + List idList = new ArrayList<>(); + List sendList = new ArrayList(); + for (int i = 0; i < mcontrolList.size(); i++) { + sendList.add(mcontrolList.get(i)); + idList.add(mcontrolList.get(i).getId()); + + if (state == 0 && sendList.size() == 50) { + // 3.2 数据发送 + String message = DataSyncUtil.generateMcontrolData(nowTerminalId, sendList); + // addTask("", nowTerminalId, message, 0, "", 0, "", "", "", + // ""); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + + "\n -> 回路发送结果,message:" + message); + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + state = result; + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update mcontrols set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + + sendList.clear(); + idList.clear(); + } + } + + if (state == 0 && !sendList.isEmpty()) { + // 3.2 数据发送 + String message = DataSyncUtil.generateMcontrolData(nowTerminalId, sendList); + // addTask("", nowTerminalId, message, 0, "", 0, "", "", "", ""); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + + "\n -> 回路发送结果,message:" + message); + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update mcontrols set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + } + + } + + public void controlSync(String nowTerminalId, List controlList, DataInstance dataInstance) + throws InterruptedException, ExecutionException { + + int state = dataInstance.getState(); + + List idList = new ArrayList<>(); + List sendList = new ArrayList(); + for (int i = 0; i < controlList.size(); i++) { + sendList.add(controlList.get(i)); + idList.add(controlList.get(i).getId()); + + if (state == 0 && sendList.size() == 50) { + + // 封装数据发送 + String message = DataSyncUtil.genetateLampData(nowTerminalId, sendList); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + + "\n -> 灯杆发送结果,message:" + message); + + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + state = result; + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update controls set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + sendList.clear(); + idList.clear(); + } + } + + if (state == 0 && !sendList.isEmpty()) { + + // 封装数据发送 + String message = DataSyncUtil.genetateLampData(nowTerminalId, sendList); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + " \r\n " + + "\n -> 灯杆发送结果,message:" + message); + + FutureTask task = new FutureTask<>(new syncTask(message)); + executorService.execute(task); + Integer result = task.get(); + dataInstance.setState(result); + + if (result == 0) { + // 更新同步进度 + updateProcess(dataInstance, nowTerminalId, sendList.size()); + + // 更新设备为 已安装 + String updateSql = " update controls set IsEffect = 1 " + + " WHERE id IN ( " + StringUtils.join(idList, ",") + " ) "; + SQLHelper.ExecSql(updateSql); + } + } + + } + + public void updateProcess(DataInstance dataInstance, String nowTerminalId, int sendCount) { + int syncedCount = dataInstance.getSyncedCount(); + int totalCount = dataInstance.getTotalCount(); + syncedCount += sendCount; + BigDecimal process = new BigDecimal(String.valueOf(syncedCount)) + .divide(new BigDecimal(String.valueOf(totalCount)), 4, BigDecimal.ROUND_HALF_UP); + dataInstance.setSyncedCount(syncedCount); + dataInstance.setProgress(process.intValue()); + + String processSql = " UPDATE datasync d LEFT JOIN terminals t ON d.terminalid = t.id " + + " SET d.progress = %s " + " WHERE t.comid = " + nowTerminalId; + SQLHelper.ExecSql(String.format(processSql, + process.multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP))); + } + + /** 485总线的巡测处理 */ + private boolean bRunBeat485 = false; + + public void RunBeat485() { + if (bRunBeat485) + return; + bRunBeat485 = true; + try { + serial485.RS485Bus_Task(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + bRunBeat485 = false; + } + + /** 国网 电表定采设置 定时处理任务 **/ + public void Run3761Timing() { + String batchtime = Common.getDateStr0(); + // 电表抄读参数 + MeterTimingParams params = SystemParameter.GetMeterTiming(); + if (params.equals("")) { + return; + } + density = params.density; + powercount = params.runNum;// 补抄次数 + powerrunHour = params.firstRunTime;// 日冻结数据抄读时间(HH:MM) + luxChangeLimit = params.luxChangeLimit;// + + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + String[] arrayHM = powerrunHour.split(":"); + Calendar calendar = Calendar.getInstance(); + String firstRunTime = ""; + try { + calendar.set(0, 0, 0, Integer.parseInt(arrayHM[0]), Integer.parseInt(arrayHM[1])); + firstRunTime = format.format(calendar.getTime()); + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + String nowtime = Common.getDateStr0(); + batchtime = nowtime.substring(0, 16) + ":00"; + + if (newcounted == 0) {// 测试 + // LampTiming(batchtime); // 曲线 + + // LampDay3761Timing(batchtime); + + // Deltempmeters();// 删除补抄结束的未抄读成功记录 + // ReDoLampReDoLamp(Common.getDateStr0()); + if (runParams.MControlTiming15 || runParams.MControlTiming60) + MControlTiming(batchtime); // 回路控制状态抄读 + // ReDoLamp(Common.getDateStr0());// 补抄处理(路灯补抄) + if (runParams.AnalysisOfTunnelElectricity) + AnalysisOfTunnelElectricity(batchtime);// 隧道用电异常报警 + newcounted++; + } + + boolean test = false; + if (test) // 系统调试 + { + if (newcounted == 0) {// 测试 + // LampTiming(batchtime); // 曲线 + + // LampDay3761Timing(batchtime); + // Deltempmeters();// 删除补抄结束的未抄读成功记录 + // MControlTiming(batchtime); // 回路控制状态抄读 + // ReDoLamp(Common.getDateStr0());// 补抄处理(路灯补抄) + AnalysisOfTunnelElectricity(batchtime);// 隧道用电异常报警 + newcounted++; + } + } else { + // 日冻结 + if (nowtime.substring(11, 16).equals(firstRunTime)) { + if (runParams.TerminalDay3761Timing) + TerminalDay3761Timing(batchtime); // 匀要不抄集中器 + + if (runParams.LampDay3761Timing) + LampDay3761Timing(batchtime); // + + // 隧道用电异常报警分析 + if (runParams.AnalysisOfTunnelElectricity) + AnalysisOfTunnelElectricity(batchtime); + + } + // 曲线数 + + // 2015-08-28 关闭曲线抄读任务 + if (density == 1) { + unitminute = 15; + int currentmin = Integer.parseInt(Common.getMinute()); + if (currentmin % 15 == 0) { + if (runParams.MControlTiming15) + MControlTiming(batchtime); // 回路控制状态抄读 + if (runParams.LampTiming) + LampTiming(batchtime); + // LampTiming(batchtime); // 匀要不抄集中器 + + } + if (currentmin % 60 == 0) { + if (runParams.MControlTiming15 == false && runParams.MControlTiming60 == true) + MControlTiming(batchtime); // 回路控制状态抄读 + if (runParams.LampTiming) + LampTiming(batchtime); + } + + } else if (density == 2) { + unitminute = 30; + int currentmin = Integer.parseInt(Common.getMinute()); + if (currentmin % 30 == 0) { + if (runParams.LampTiming) + LampTiming(batchtime); + } + } else if (density == 3) { + unitminute = 60; + int currentmin = Integer.parseInt(Common.getMinute()); + if (currentmin % 60 == 0) { + if (runParams.LampTiming) + LampTiming(batchtime); + } + } + + // Deltempmeters();// 删除补抄结束的未抄读成功记录 + // ReDoLamp(Common.getDateStr0());// 补抄处理(路灯补抄) + } + } + + /** + * 电表定采 日冻 + */ + public void Day3761Timing(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read Meter Days freezing]");// 电表定采 + // 日冻 + Reconnect(); + + boolean blday = false; + SimpleDateFormat format; + + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + // RunParams runParams; + // runParams = Protocol.systemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + + Date currDate = new Date(); + try { + Integer pn = 0; + Integer intProject = 0;// 定采方案 + String strItems = "";// 定采抄读项目 + String nocurve = "3,4,5"; + String usertype = "";// 用户大类号(为3,4,5时无曲线数据) + String tcomid = "";// 电表通信地址 + String comtype = "";// 通信类型 + String cmdcode = "";// 下行报文 + String protocol = "";// 协议类型 + String cdomain = "6B";// 控制域 + String afn = "0D";// 应用层功能码 + String afncode = "";// 补抄表中的,afn:fn + int comport = 2; // 通信端口 + Integer[] fns = new Integer[] { 81, 85, 89, 90, 91, 92, 93, 94, 95, 101, 102, 103, 104, 105, 161, 162, 163, + 164 }; + String[] codes = new String[] { "2011", "2012", "2005", "2006", "2007", "2008", "2009", "2010", "2014", + "2001", "2002", "2003", "2004", "2013", "1001", "1003", "1002", "1004" }; + + Integer[] temp_fns = new Integer[0]; + String strsql = ""; + String params = ""; + String[] array; + + // 获取 可抄读的功能码 + List dayList = new ArrayList(); + List curveList = new ArrayList(); + strsql = "SELECT code FROM syscode WHERE type =26 AND remark='1' "; + Statement stmt1 = null; + ResultSet rSet1 = SQLHelper.getResultSet(strsql); + if (rSet1 == null) { + return; + } + List tempList = new ArrayList(); + tempList.add("0006"); // 灯控器巡测数据 + tempList.add("0051"); // 主控开关小时冻结交采数据 + String tempString = ""; + while (rSet1.next()) { + tempString = rSet1.getString("code"); + if (tempList.indexOf(tempString) > -1) + curveList.add(tempString); + else + dayList.add(tempString); + + } + + // 查询meters 只加载国网 + + // 获取数量 + strsql = "select count(*) num from meters m join terminals t on m.terminal=t.comid where t.protocol<>'0001' and iseffect=1 "; + stmt1 = null; + rSet1 = SQLHelper.getResultSet(strsql); + if (rSet1 == null) { + return; + } + int rowCount = 0; + while (rSet1.next()) { + rowCount = rSet1.getInt("num"); + } + + strsql = "select m.comport,m.terminal, m.no,t.commodel,m.usertype,t.protocol,t.object from meters m join terminals t on m.terminal=t.comid where t.protocol<>'0001' and iseffect=1 order by m.terminal,m.no"; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int i = 0; + int fn = 0; + List PnList = new ArrayList(); + String DA = ""; + String DT = ""; + String lastTerminalString = ""; + try { + int curRow = 0; + while (rSet.next()) { + curRow++; + tcomid = rSet.getString("terminal"); + pn = rSet.getInt("no"); + PnList.add(pn); + comtype = rSet.getString("commodel"); + usertype = rSet.getString("usertype"); + protocol = rSet.getString("protocol"); + comport = rSet.getInt("comport"); + + // 生成 日冻结 一个测量点一个数据标识 + for (i = 0; i < dayList.size(); i++) { + fn = Integer.valueOf(String.valueOf(dayList.get(i))); + + DA = GW3761.GetDAOrDT(pn, 0); + DT = GW3761.GetDAOrDT(fn, 1); + Protocol.wtempmeters(tcomid, DA + DT, comtype, 0, Common.getYesterdayStr7(), intervalTiming); + // Create3761DayTask(tcomid,fn,pn,currDate,comtype + // ,intervalTiming); + } + + if (curveList.indexOf("51") > -1) { + DA = GW3761.GetDAOrDT(pn, 0); + DT = GW3761.GetDAOrDT(fn, 1); + Calendar cal = Calendar.getInstance(); + cal.setTime(currDate); + cal.add(Calendar.DATE, -1); + SimpleDateFormat format1 = new SimpleDateFormat("ddMMyy"); + Protocol.wtempmeters(tcomid, DA + DT + "0000" + format1.format(cal.getTime()) + "030C", comtype, + 0, Common.getYesterdayStr7(), intervalTiming); + Protocol.wtempmeters(tcomid, DA + DT + "0012" + format1.format(cal.getTime()) + "030C", comtype, + 0, Common.getYesterdayStr7(), intervalTiming); + + } + + if (curRow < rowCount) { + if (tcomid.equals(lastTerminalString) && PnList.size() < meterParams.packsize) { + continue; + } + } + lastTerminalString = tcomid; + if (PnList.size() == 0 || (PnList.size() < meterParams.packsize && curRow < rowCount)) { + continue; + } + // 曲线 主控开关小时冻结交采数据 52 灯控器巡测数据 F6 + for (i = 0; i < curveList.size(); i++) { + fn = Integer.valueOf(String.valueOf(dayList.get(i))); + if (fn == 52) + continue; + Create3761Task(tcomid, fn, PnList, currDate, comtype, intervalTiming); + } + PnList.clear(); + } + } catch (SQLException e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2:" + e.getMessage()); + } + if (blday) + readedday = Common.getDateStr7(); + Deltempmeters();// 删除补抄结束的未抄读成功记录 + ReDo(batchtime);// 补抄处理 + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR3:" + e.getMessage()); + } + } + + /** + * 批量生成 3761 的抄表任务书(日冻结) + * + * @param tcomid + * 集中器通信地址 + * @param fn + * 功能码 + * @param pn + * 测量点 + * @param createDate + * 生成时间 + * @param comtype + * 通信通道类型 + * @param intervalTiming + * 补抄运行间隔 + */ + public static void Create3761DayTask(String tcomid, int fn, int pn, Date createDate, String comtype, + Integer intervalTiming) { + String params = ""; + String cdomain = "6B";// 控制域 + String afn = "AC";// 应用层功能码 + char[] chars = tcomid.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + String DA = GW3761.GetDAOrDT(pn, 0); + String DT = GW3761.GetDAOrDT(fn, 1); + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Protocol.wtempmeters(tcomid, DA + DT, comtype, 0, format1.format(createDate), intervalTiming); + // PnList.clear(); + if (PFC == 255) { + PFC = 0; + } + PFC += 1; + } + + /** + * 批量生成 3761 的抄表任务书(曲线 ) + * + * @param tcomid + * 集中器通信地址 + * @param fn + * 功能码 + * @param pn + * 测量点 + * @param createDate + * 生成时间 + * @param comtype + * 通信通道类型 + * @param intervalTiming + * 补抄运行间隔 + */ + public static void Create3761CurveTask(String tcomid, int fn, int pn, Date createDate, String comtype, + Integer intervalTiming) { + + String DA = GW3761.GetDAOrDT(pn, 0); + String DT = GW3761.GetDAOrDT(fn, 1); + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Protocol.wtempmeters(tcomid, DA + DT, comtype, 0, format1.format(createDate), intervalTiming); + + } + + /** + * 批量生成 3761 的抄表任务书 + * + * @param tcomid + * 集中器通信地址 + * @param fn + * 功能码 + * @param PnList + * 测量点 + * @param createDate + * 生成时间 + * @param comtype + * 通信通道类型 + * @param intervalTiming + * 补抄运行间隔 + */ + public static void Create3761Task(String tcomid, int fn, List PnList, Date createDate, String comtype, + Integer intervalTiming) { + String params = ""; + String cdomain = "6B";// 控制域 + String afn = "AD";// 应用层功能码 + char[] chars = tcomid.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + if (fn == 1) { // 曲线类数据时标Td_c:分时日月年(5字节)+数据冻结密度m(1字节)+数据点数n(1字节) + SimpleDateFormat format = new SimpleDateFormat("mmHHddMMyy"); + Calendar cal = Calendar.getInstance(); + cal.setTime(createDate); + + int minutes = (createDate.getMinutes() / unitminute - 1) * unitminute; + cal.set(Calendar.MINUTE, minutes); + + params = format.format(cal.getTime()) + Common.right("00" + String.valueOf(density), 2) + "01"; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "-> 曲线时标" + cal.getTime().getMinutes()); + + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "-> 曲线时标" + params); + } else { + // 日冻结类数据时标Td_d:日月年(3字节) + params = Common.meterGetTd_d(); + } + + if (fn == 6) + params = Common.meterGetTd_d(); + // 生成抄读指令 + if (!params.equals("")) { + + String str = ""; + for (int i = 0; i < PnList.size(); i++) { + int pn = (Integer) PnList.get(i); + String DA = GW3761.GetDAOrDT(pn, 0); + String DT = GW3761.GetDAOrDT(fn, 1); + str = str + DA + DT + params; + } + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Protocol.wtempmeters(tcomid, str, comtype, 0, format1.format(createDate), intervalTiming); + // PnList.clear(); + if (PFC == 255) { + PFC = 0; + } + PFC += 1; + } + params = ""; + } + + /** + * 批量生成 3761 的抄表任务书 + * + * @param tcomid + * 集中器通信地址 + * @param fn + * 功能码 + * @param PnList + * 测量点 + * @param createDate + * 生成时间 + * @param comtype + * 通信通道类型 + * @param intervalTiming + * 补抄运行间隔 + */ + public static void Create3761LampTask(String tcomid, int fn, List PnList, Date createDate, String comtype, + Integer intervalTiming, String... StrAFNs) { + if (PnList != null) + if (PnList.size() == 0) + return; + + String params = ""; + String strAfn = ""; + if (null == StrAFNs || StrAFNs.length == 0) // 数params是被作为一个数组对待的 + strAfn = ""; + else + strAfn = StrAFNs[0].toUpperCase(); + + // 2019-01-19 wwb 增加 灯控器日冻结数据 + if (strAfn.equals("AD") && fn == 70) // F70:单灯电能日冻结数据 + { + for (int i = 0; i < PnList.size(); i++) { + String str = Common.dec2Hex((Integer) PnList.get(i), 4); + params = params + str.substring(2) + str.substring(0, 2); + } + String msg = "0000" + GW3761.GetDAOrDT(fn, 1) + Common.getTd_d(createDate) + + Common.dec2Hex(PnList.size(), 2) + params; + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + GW3761.wtempmeters(tcomid, msg, comtype, fn, format1.format(createDate), intervalTiming); + } + + else if (fn == 60) {// 回路控制状态曲线 + String msg = GW3761.GetDAOrDT((Integer) PnList.get(0), 0) + GW3761.GetDAOrDT(fn, 1) + + Common.meterGetTd_c(createDate);// 一小时前的时间 + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + GW3761.wtempmeters(tcomid, msg, comtype, fn, format1.format(createDate), intervalTiming); + } else if (fn == 7) { + for (int i = 0; i < PnList.size(); i++) { + String str = Common.dec2Hex((Integer) PnList.get(i), 4); + params = params + str.substring(2) + str.substring(0, 2); + } + String msg = "0000" + GW3761.GetDAOrDT(fn, 1) + Common.dec2Hex(PnList.size(), 2) + params; + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + GW3761.wtempmeters(tcomid, msg, comtype, 7, format1.format(createDate), intervalTiming); + } else { + + String msg = "0000" + GW3761.GetDAOrDT(fn, 1); + SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + GW3761.wtempmeters(tcomid, msg, comtype, fn, format1.format(createDate), intervalTiming); + } + + } + + /** + * 日冻结定 (集中器) + * + * @param batchtime + */ + public static void TerminalDay3761Timing(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read Terminal Days freezing]");// 路灯定采 + // 日冻 + Reconnect(); + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + Date currDate = new Date(); + try { + String strsql = "SELECT comid,commodel,object FROM terminals"; + Statement stmt1 = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int packSize = 40; + String comtype = ""; + String tcomid = ""; + String object = ""; + String strsql1 = ""; + while (rSet.next()) { + tcomid = rSet.getString("comid"); + comtype = rSet.getString("commodel"); + + object = rSet.getString("object"); + // 定采方案 即用户自定义部份 + if (object != null && !object.equals("")) { + TerminalDay3761Timing_Project(tcomid, object, currDate, comtype, intervalTiming); + } + + // 昨天A、B、C相及有功功率 + Create3761LampTask(tcomid, 25, null, currDate, comtype, intervalTiming); + + // 昨天总功率因数/三相功率因数 + Create3761LampTask(tcomid, 31, null, currDate, comtype, intervalTiming); + + // 昨天总有功功率 + Create3761LampTask(tcomid, 33, null, currDate, comtype, intervalTiming); + + // 昨天三相电压 + Create3761LampTask(tcomid, 35, null, currDate, comtype, intervalTiming); + + // 昨天三相电流 + Create3761LampTask(tcomid, 38, null, currDate, comtype, intervalTiming); + + // 昨日正向有功电能量 + Create3761LampTask(tcomid, 41, null, currDate, comtype, intervalTiming); + + } + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + // ReDoLamp(Common.getDateStr0()); + } + + /** + * 用户自定义 定采方案处理(集中器参数) + * + * @param tcomid + * 集中器 + * @param project + * 定采方案ID + * @param currDate + * 生成时间 + * @param comtype + * 通信通道类型 + * @param intervalTiming + * 抄读间隔 + */ + public static void TerminalDay3761Timing_Project(String tcomid, String project, Date currDate, String comtype, + int intervalTiming) { + + try { + String strsql = "SELECT item FROM projects where recordid = " + project; + Statement stmt1 = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + while (rSet.next()) { + String itemString = rSet.getString("item"); + if (itemString == null) + continue; + String[] readItem = itemString.split(","); + for (int i = 0; i < readItem.length; i++) { + String str = readItem[i]; + // 昨天三相电流 + if (str == null || str.equals("")) + continue; + + if (str.equals("1243")) // PM2.5 + Create3761LampTask(tcomid, 43, null, currDate, comtype, intervalTiming); + + } + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 路灯曲线 定采任务 + * + * @param batchtime + * 定采任务时间 + */ + public void MControlTiming(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read MControl Datas]");// 路灯定采 + // 曲线 + Reconnect(); + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + Date currDate = new Date(); + + /* + * String dateString = "2017-10-15 11:30:00"; SimpleDateFormat sdf = new + * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { currDate = + * sdf.parse(dateString); currDate = new Date(currDate.getTime() + + * (long) 15 * 60 * 1000); } catch (ParseException e1) { + * e1.printStackTrace(); } + */ + + currDate = new Date(currDate.getTime() - (long) 15 * 60 * 1000); + Date currDate1 = new Date(currDate.getTime() - (long) 60 * 60 * 1000); + try { + String strsql = ""; + strsql = "SELECT num, t.ComModel,m.terminal,t.ConModel FROM mcontrols m join terminals t on m.terminal=t.comid " + + " where iseffect=1 " + " and t.comid IN ( " + + " SELECT comid FROM terminals WHERE object IN (SELECT recordid FROM projects WHERE charindex('0002',projects.Item)=1) " + + ")" + " order by m.terminal "; + Statement stmt1 = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int fn = 60; + int packSize = 40; + List PnList = new ArrayList(); + String comtype = ""; + String tcomid = ""; + String ConModel = ""; + while (rSet.next()) { + tcomid = rSet.getString("terminal"); + comtype = rSet.getString("commodel"); + // AD + PnList.clear(); + PnList.add(rSet.getInt("num")); + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming); + PnList.clear(); + // AC + /* + * if (!str.equals(tcomid) && !tcomid.equals("")) { + * Create3761LampTask(tcomid, fn, PnList, currDate, comtype, + * intervalTiming); PnList.clear(); comtype = + * rSet.getString("commodel"); ConModel = + * rSet.getString("ConModel"); tcomid = str; } + * PnList.add(rSet.getInt("num")); if (PnList.size() >= + * packSize) { Create3761Task(tcomid, fn, PnList, currDate, + * comtype, intervalTiming); PnList.clear(); } + */ + } + // Create3761LampTask(tcomid, fn, PnList, currDate, comtype, + // intervalTiming); + // PnList.clear(); + + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read MControl Datas Complete!]");// 路灯定采 + // 曲线 + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 路灯曲线 定采任务 + * + * @param batchtime + */ + public static void LampTiming(String batchtime) { + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read Lamp Datas]");// 路灯定采 + // 曲线 + Reconnect(); + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + Date currDate = new Date(); + try { + String strsql = ""; + strsql = "SELECT num, t.ComModel,m.terminal,t.ConModel FROM controls m join terminals t on m.terminal=t.comid " + + " where iseffect=1 " + " and t.comid IN ( " + + " SELECT comid FROM terminals WHERE object IN (SELECT recordid FROM projects WHERE charindex('0001',projects.Item)>0) " + + ")" + " order by m.terminal "; + Statement stmt1 = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int fn = 7; + int packSize = 40; + List PnList = new ArrayList(); + String comtype = ""; + String tcomid = ""; + String ConModel = ""; + while (rSet.next()) { + String str = rSet.getString("terminal"); + + if (!str.equals(tcomid)) { + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming); + PnList.clear(); + comtype = rSet.getString("commodel"); + ConModel = rSet.getString("ConModel"); + tcomid = str; + } + PnList.add(rSet.getInt("num")); + if (PnList.size() >= packSize) { + + if (ConModel.equals("0001")) // 灯控器巡测数据2 + Create3761LampTask(tcomid, 7, PnList, currDate, comtype, intervalTiming); + else + // 色温灯控器巡测数据2 + Create3761LampTask(tcomid, 9, PnList, currDate, comtype, intervalTiming); + + PnList.clear(); + } + } + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming); + PnList.clear(); + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 隧道用电分析 每个隧道安装一台集中器, 隧道用电量等线路用户电量的累加和 + * + * @param batchtime + */ + public static void AnalysisOfTunnelElectricity(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[AnalysisOfTunnelElectricity]");// 隧道用电分析 + Reconnect(); + String today = Common.getDateStr7(); + // today="2019-05-22"; + String strsql = ""; + String limit = "20"; + ResultSet rSet; + try { + strsql = "select content from syscode where type=45 and code='0001'"; + rSet = SQLHelper.getResultSet(strsql); + while (rSet.next()) { + limit = rSet.getString("content"); + } + } catch (Exception e) { + limit = "20"; + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + strsql = " SELECT daycount,dayhappen,terminal,LASTcount,LASThappen,(abs(dayhappen-LASThappen)/LASThappen*100) " + + "FROM " + "(" + "SELECT count(terminal) daycount,sum(happen) dayhappen,terminal," + + " (SELECT count(terminal) FROM daydatas a " + + " WHERE a.datadate=CONVERT(varchar(100), dateadd(day,-1,'" + today + "' ), 23) " + + " and a.terminal=terminal AND types='0004') LASTcount ," + + " (SELECT count(happen) FROM daydatas a " + + " WHERE a.datadate=CONVERT(varchar(100), dateadd(day,-1,'" + today + "' ), 23) " + + " and a.terminal=terminal AND types='0004') LASThappen " + "FROM daydatas d WHERE " + + " datadate='" + today + "' AND types='0004' GROUP BY terminal ) aa " + + " WHERE daycount=LASTcount AND (abs(dayhappen-LASThappen)/LASThappen*100)> " + limit; + + rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + while (rSet.next()) { + String terminal = rSet.getString("terminal"); + // 写入事情 + gw3761.InsertEventInfo(Common.getDateStr0(), terminal, 0, "", "", 32, "用电异常", "", "", 0); + + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 路灯日冻结 定采任务(当前只抄读 灯具 冻结 电能量) + * + * @param batchtime + */ + public static void LampDay3761Timing(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read Lamp Days freezing]");// 路灯定采 + // 曲线 + Reconnect(); + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + Date currDate = new Date(); + try { + String strsql = ""; + strsql = "SELECT num, t.ComModel,m.terminal,t.ConModel FROM controls m join terminals t on m.terminal=t.comid " + + " where iseffect=1 " + " and t.comid IN ( " + + " SELECT comid FROM terminals WHERE object IN (SELECT recordid FROM projects WHERE charindex('0007',projects.Item)=1) " + + ")" + " order by m.terminal "; + Statement stmt1 = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int fn = 70; // AD F70:单灯电能日冻结数据 + int packSize = 40; + List PnList = new ArrayList(); + String comtype = ""; + String tcomid = ""; + String ConModel = ""; + while (rSet.next()) { + String str = rSet.getString("terminal"); + + if (!str.equals(tcomid)) { + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming); + PnList.clear(); + comtype = rSet.getString("commodel"); + ConModel = rSet.getString("ConModel"); + tcomid = str; + } + PnList.add(rSet.getInt("num")); + if (PnList.size() >= packSize) { + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming, "AD"); + + PnList.clear(); + } + } + Create3761LampTask(tcomid, fn, PnList, currDate, comtype, intervalTiming, "AD"); + PnList.clear(); + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 灯曲线 任务执行 + * + * @param batchtime + */ + public void ReDoLamp(String batchtime) { + if (timer_redo_run == true) + return; + timer_redo_run = true; + + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->Run " + batchtime); + String tcomid = ""; + String comtype = ""; + String protocol = "0001";// 协议类型 + String cmdcode = ""; + String runTime = ""; + String strtd = ""; + String idString = ""; + int fn = 0; + int intervalTimming = 0; + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + format.setTimeZone(TimeZone.getTimeZone("GMT+8")); + String strsql = "select id,terminal,no, commodel,code,td,intervalTiming,protocol from tempmeters where count<" + + powercount + " and runTime<='" + batchtime + "' order by terminal"; + ResultSet rSet = SQLHelper.getResultSet(strsql); + // Log.writelog(clazzName,"ReDoByLon16()->sql:" + strsql); + if (rSet == null) { + return; + } + try { + while (rSet.next()) { + idString = rSet.getString("id"); + tcomid = rSet.getString("terminal"); + comtype = rSet.getString("commodel"); + cmdcode = rSet.getString("code"); + intervalTimming = rSet.getInt("intervalTiming"); + strtd = rSet.getString("td"); + protocol = rSet.getString("protocol"); + idString = rSet.getString("id"); + fn = rSet.getInt("no"); + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->:" + tcomid + + " " + cmdcode + " " + strtd + " " + protocol); + // 进行补抄 + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = tcomid.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + + if (fn == 60 || fn == 70) {// F60:回路状态曲线 F70:单灯电能日冻结数据 + cmdcode = gw3761.create3761("6B", adomain, "AD", seqdomain, cmdcode); + WriteData(comtype, tcomid, cmdcode, protocol, "AD", fn, strtd, "0", idString); + } else { + cmdcode = gw3761.create3761("6B", adomain, "AC", seqdomain, cmdcode); + WriteData(comtype, tcomid, cmdcode, protocol, "AC", fn, strtd, "0", idString); + } + // 更新下一次运行时间,以及补抄运行次数 + String updateSql = ""; + if (fn == 7) // 灯控器的运行数据 + { + updateSql = "delete tempmeters where id=" + idString; + } else { + // 更新下一次运行时间,以及补抄运行次数 + String[] arrayHM = batchtime.substring(11).split(":"); + Calendar calendar = Calendar.getInstance(); + calendar.set(0, 0, 0, Integer.parseInt(arrayHM[0].trim()), Integer.parseInt(arrayHM[1].trim())); + calendar.add(Calendar.MINUTE, intervalTimming); + runTime = format.format(calendar.getTime()); + runTime = Common.getDateStr7() + " " + runTime + ":00"; + updateSql = "update tempmeters set count=count+1,runtime='" + runTime + "'" + " where id=" + + idString; + } + SQLHelper.ExecSql(updateSql); + + // 删除昨天的抄表数据 + } + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Run complete!" + batchtime); + } catch (SQLException e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + try { + Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR1:" + e.getMessage()); + } + timer_redo_run = false; + } + + /** + * 电表定采执行(无时间标签) + */ + public void PowerTiming(String batchtime) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[Read Meter Datas]");// 电表定采 + // 曲线 + Reconnect(); + + boolean blday = false; + SimpleDateFormat format; + + MeterTimingParams meterParams = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (meterParams == null) { + return; + } + int intervalTiming = meterParams.intervalTiming;// 间隔时间(分) + String firstRunTime = meterParams.firstRunTime; // 日冻结 + + Date currDate = new Date(); + try { + Integer pn = 0; + Integer intProject = 0;// 定采方案 + String strItems = "";// 定采抄读项目 + String nocurve = "3,4,5"; + String usertype = "";// 用户大类号(为3,4,5时无曲线数据) + String tcomid = "";// 电表通信地址 + String comtype = "";// 通信类型 + String cmdcode = "";// 下行报文 + String protocol = "";// 协议类型 + String cdomain = "6B";// 控制域 + String afn = "0D";// 应用层功能码 + String afncode = "";// 补抄表中的,afn:fn + int comport = 2; // 通信端口 + Integer[] fns = new Integer[] { 81, 85, 89, 90, 91, 92, 93, 94, 95, 101, 102, 103, 104, 105, 161, 162, 163, + 164 }; + String[] codes = new String[] { "2011", "2012", "2005", "2006", "2007", "2008", "2009", "2010", "2014", + "2001", "2002", "2003", "2004", "2013", "1001", "1003", "1002", "1004" }; + + Integer[] temp_fns = new Integer[0]; + String strsql = ""; + String params = ""; + String[] array; + + // 查询meters 只加载国网 + strsql = "select count(*) num from meters m join terminals t on m.terminal=t.comid where t.protocol<>'0001' and m.comport < 5 and iseffect=1 "; + Statement stmt1 = null; + ResultSet rSet1 = SQLHelper.getResultSet(strsql); + if (rSet1 == null) { + return; + } + int rowCount = 0; + while (rSet1.next()) { + rowCount = rSet1.getInt("num"); + } + + strsql = "select m.comport,m.terminal, m.no,t.commodel,m.usertype,t.protocol,t.object from meters m join terminals t on m.terminal=t.comid where t.protocol<>'0001' and m.comport < 5 and iseffect=1 order by m.terminal,m.no"; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + List PnList = new ArrayList(); + String lastTerminalString = ""; + try { + int curRow = 0; + while (rSet.next()) { + curRow++; + tcomid = rSet.getString("terminal"); + pn = rSet.getInt("no"); + PnList.add(pn); + comtype = rSet.getString("commodel"); + usertype = rSet.getString("usertype"); + protocol = rSet.getString("protocol"); + comport = rSet.getInt("comport"); + if (curRow < rowCount) { + if (tcomid.equals(lastTerminalString) && PnList.size() < meterParams.packsize) { + continue; + } + } + lastTerminalString = tcomid; + if (PnList.size() == 0 || PnList.size() < meterParams.packsize) { + continue; + } + + if (Common.isNumeric(rSet.getString("object"))) { + intProject = rSet.getInt("object"); + } else { + intProject = 0; + } + + if (intProject != 0) { + // 根据集中器定采方案获取定采抄读项目 + strsql = "select Item from projects where recordid=" + intProject; + Statement stmts = null; + ResultSet rSetProject = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + try { + while (rSetProject.next()) { + strItems = rSetProject.getString("Item"); + } + } catch (Exception e) { + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.getMessage()); + } + try { + stmts = rSetProject.getStatement(); + rSetProject.close(); + stmts.close(); + rSetProject = null; + stmts = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR1:" + e.getMessage()); + } + + array = strItems.split(","); + ArrayList arrayList = new ArrayList(); + for (String str : array) { + for (int i = 0; i < codes.length; i++) { + if (str.equals(codes[i])) { + arrayList.add(fns[i]); + break; + } + } + } + + temp_fns = null; + if (arrayList.size() > 0) { + temp_fns = (Integer[]) arrayList.toArray(new Integer[arrayList.size()]); + } + } + + // 地址域 + // char[] chars = tcomid.toCharArray(); + // String adomain = String.valueOf(chars[2]) + + // String.valueOf(chars[3]) + String.valueOf(chars[0]) + + // String.valueOf(chars[1]) + String.valueOf(chars[6]) + + // String.valueOf(chars[7]) + // + String.valueOf(chars[4]) + String.valueOf(chars[5]) + + // "04"; + + if (temp_fns != null) { + for (Integer fn : temp_fns) { + if (fn < 160) // 处理曲线 + Create3761Task(tcomid, fn, PnList, currDate, comtype, intervalTiming); + } + } + PnList.clear(); + } + } catch (SQLException e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR2:" + e.getMessage()); + } + if (blday) + readedday = Common.getDateStr7(); + Deltempmeters();// 删除补抄结束的未抄读成功记录 + ReDo(batchtime);// 补抄处理 + + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR3:" + e.getMessage()); + } + } + + /** + * LON16集中器定时抄表 + */ + public void runLon16Timing() { + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + int hour = 0; + int minute = 0; + String batchtime = ""; + String[] array; + // 获取定采参数 + MeterTimingParams params = SystemParameter.GetMeterTiming(); + RunParams runParams; + runParams = SystemParameter.runParams; + if (params == null) { + return; + } + int intervalTiming = params.intervalTiming;// 间隔时间(分) + int runNum = params.runNum;// 运行次数 补抄次数 + String firstRunTime = params.firstRunTime;// 新集中器的定采开始时间 + + String[] arrayHM = firstRunTime.split(":"); + Calendar calendar = Calendar.getInstance(); + try { + calendar.set(0, 0, 0, Integer.parseInt(arrayHM[0]), Integer.parseInt(arrayHM[1])); + firstRunTime = format.format(calendar.getTime()); + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + if (newcounted == 0) // 测试代码 + { + batchtime = Common.getDateStr7() + " " + firstRunTime + ":00"; + // lon16TimingGeneral(runNum,intervalTiming, batchtime); + // lon16TimingMulti(runNum,intervalTiming, batchtime); + newcounted++; + } + String nowtime = Common.getDateStr0(); + batchtime = nowtime.substring(0, 16) + ":00"; + // 生成抄表数据 + if (nowtime.substring(11, 16).equals(firstRunTime)) { + // 生成普通表的抄表任务 + lon16TimingGeneral(runNum, intervalTiming, batchtime); + // 生成普通表(多费率)的抄表任务 + lon16TimingRate(runNum, intervalTiming, batchtime); + // 生成用户多功能的抄表任务 + lon16TimingMulti(runNum, intervalTiming, batchtime); + // 生成台区考核表的抄表任务 + lon16TimingChkM(runNum, intervalTiming, batchtime); + } + + Deltempmeters();// 删除补抄结束的未抄读成功记录 + ReDo(batchtime);// 补抄处理 + + } + + /** + * lon16 普通表 定采数据生成 + * + * @param runTime + * 补抄次数 + * @param intervalTiming + * 补抄间隔 + * @param batchtime + * 任务时间 + */ + private void lon16TimingGeneral(int runTime, int intervalTiming, String batchtime) { + + // 获取普通表 + String strsql = "SELECT b.comid,commodel,count(a.comid) num FROM meters a,terminals b WHERE a.terminal = b.comid " + + "AND a.usertype='5' AND b.protocol='0001' GROUP BY b.commodel,b.comid"; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + String Tcomid = ""; + String Mcomid = ""; + String comType = ""; + int meterNum = 0; + int packSize = 12; + int packNum = 0; + String cmd = ""; + if (rSet != null) { + try { + while (rSet.next()) { + Tcomid = rSet.getString("comid"); + comType = rSet.getString("commodel"); + meterNum = Integer.valueOf(rSet.getString("num")); + // 计算GRB命令 + packNum = meterNum / packSize; + if ((meterNum % packSize) > 0) { + packNum++; + } + for (int i = 0; i < packNum; i++) { + cmd = "GRB" + com.back.common.Common.lPad(String.valueOf(i * packSize), 4, "0") + + com.back.common.Common.lPad(String.valueOf(packSize), 2, "0") + "F02041005037071"; + + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + + // 加载到任务对列里 + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "-> create Cmd:" + cmd); + WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, "0", ""); + + } + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "-> ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * lon16 多费率 定采数据生成 + * + * @param runTime + * 补抄次数 + * @param intervalTiming + * 补抄间隔 + * @param batchtime + * 任务时间 + */ + private void lon16TimingRate(int runTime, int intervalTiming, String batchtime) { + // 获取普通表 + String strsql = "SELECT b.comid tcomid,commodel,a.comid FROM meters a,terminals b WHERE a.terminal = b.comid " + + "AND a.usertype='5' AND b.protocol='0001' and a.rate>0"; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + String Tcomid; + String Mcomid; + String comType; + int packNum = 0; + String cmd = ""; + if (rSet != null) { + try { + while (rSet.next()) { + Tcomid = rSet.getString("tcomid"); + comType = rSet.getString("commodel"); + Mcomid = rSet.getString("comid"); + // 计算抄命令 F040607080910 + cmd = "R" + com.back.common.Common.lPad(Mcomid, 12, "0") + "F040607080910"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // 加载到任务对列里 + WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, "0", ""); + + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * lon16 用户多功能 定采数据生成 () + * + * @param runTime + * 补抄次数 + * @param intervalTiming + * 补抄间隔 + * @param batchtime + * 任务时间 + */ + private void lon16TimingMulti(int runTime, int intervalTiming, String batchtime) { + // 获取普通表 + String strsql = "SELECT b.comid,commodel FROM meters a,terminals b WHERE a.terminal = b.comid " + + "AND a.usertype='3' AND b.protocol='0001' "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + String Tcomid; + String Mcomid; + String comType; + String cmd = ""; + int rowNum = 0; + if (rSet != null) { + try { + while (rSet.next()) { + Tcomid = rSet.getString("comid"); + comType = rSet.getString("commodel"); + Mcomid = rSet.getString("comid"); + // 计算抄命令 F0203040506070809 + cmd = "R1" + com.back.common.Common.lPad(String.valueOf(rowNum), 3, "0") + "F03040506070809"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // 加载到任务对列里 + WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, "0", ""); + + // 计算抄命令 F7071 + cmd = "R1" + com.back.common.Common.lPad(String.valueOf(rowNum), 3, "0") + "F02707109"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // 加载到任务对列里 + WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, "0", ""); + + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * lon16 普通表 定采数据生成 + * + * @param runTime + * 补抄次数 + * @param intervalTiming + * 补抄间隔 + * @param batchtime + * 任务时间 + */ + private static void lon16TimingChkM(int runTime, int intervalTiming, String batchtime) { + // 获取普通表 + String strsql = "SELECT b.comid tcomid,commodel FROM meters a,terminals b WHERE a.terminal = b.comid " + + "AND a.usertype='6' AND b.protocol='0001' "; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + String Tcomid; + String comType; + String cmd = ""; + if (rSet != null) { + try { + while (rSet.next()) { + + Tcomid = rSet.getString("tcomid"); + comType = rSet.getString("commodel"); + // 计算抄命令 台区表的电量数据 + + cmd = "R3000F03040506070809"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, + // "0", ""); + + // 读取生产数据 + cmd = "R3000F282930313233"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, + // "0", ""); + + cmd = "R3000F343536373839"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, + // "0", ""); + + cmd = "R3000F404142434445"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, + // "0", ""); + + cmd = "R3000F464748495051"; + // 添加到补抄表中 + Lon16.wtempmeters(Tcomid, cmd, comType, batchtime, intervalTiming); + // WriteData(comType, Tcomid, cmd, "0001", "", 0, batchtime, + // "0", ""); + + } + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + // 获取用户多功能 + + // 获取台区考核表 + + } + + /** + * + * @param ruletype + * 通信协议 + * @param terminal + * 集中器通信地址 + * @param cmdcode + * 下行报文 + * @param cmdid + * 指令ID + * @param afncode + * 电表抄读使用 + * @param pn + * 功能码 + * @param wtime + * 写入时间 + * @param batchtime + * 批量处理时间 + * @param responsetype + * 应答类型 0 处理应答 1 不处理应签 2 光控应答处理 + * @param idString + * 页面命令ID + */ + public static void addTask(String ruletype, String terminal, String cmdcode, int cmdid, String afncode, int pn, + String wtime, String batchtime, String responsetype, String idString) { + SocketComm sCom = new SocketComm(Work.language); + String ipString = gprsIp; + int port = gprsPort; + if (ruletype.equals("0001")) // Lon16 + { + ipString = gprsIpLon; + port = gprsPortLon; + } + threadPool.execute(terminal, cmdid, createTask(sCom, ruletype, terminal, cmdcode, cmdid, ipString, port, reSend, + gprsTimeOut, afncode, pn, wtime, batchtime, responsetype, idString));// 启动任务 + } + + /** 执行任务 */ + private static Thread createTask(final SocketComm socket, final String ruletype, final String terminal, + final String command, final Integer cmdid, final String ipadd, final Integer port, final int resend, + final int timeout, final String afncode, final int pn, final String wtime, final String batchtime, + final String responsetype, final String idString) { + return new Thread() { + public void run() { + String threadid = String.valueOf(Thread.currentThread().getId()); // 任务ID + + if (!wtime.equals("")) {// 转发指令时需判断转发指令是否超时 + Calendar calendar = Calendar.getInstance(); + int second = calendar.get(Calendar.SECOND); + calendar.set(Calendar.SECOND, second - timeDiscard); + + Date dt1 = Common.formattime3(wtime); + if (dt1.after(calendar.getTime())) { + // 发送接收 处理 + socket.Send(threadid, ruletype, terminal, command, cmdid, ipadd, port, resend, timeout, afncode, + pn, batchtime, responsetype, idString); + } + } else { + socket.Send(threadid, ruletype, terminal, command, cmdid, ipadd, port, resend, timeout, afncode, pn, + batchtime, responsetype, idString); + } + threadPool.terminaListRemove(terminal); + } + }; + } + + public void syncTask(String terminal, final String message) { + + Thread thread = new Thread() { + + @Override + public void run() { + String ipadd = gprsIp; + int port = gprsPort; + // if (ruletype.equals("0001")) // Lon16 + // { + // ipString = gprsIpLon; + // port = gprsPortLon; + // } + int timeout = 0; + + int state = 0; + + Socket socket = null; + // 获得对应socket的输入/输出流 + InputStream is = null; + OutputStream os = null; + // 建立数据流 + DataInputStream dis = null; + DataOutputStream dos = null; + + try { + socket = new Socket(ipadd, port); + } catch (Exception e) {// socket连接失败 + state = 4;// GPRS服务器连接失败 + return; + } + + try { + socket.setSoTimeout(timeout);// 设置超时时间 + // 获得对应socket的输入/输出流 + is = socket.getInputStream(); + os = socket.getOutputStream(); + // 建立数据流 + dis = new DataInputStream(is); + dos = new DataOutputStream(os); + + byte[] getbytes; + int len; + + // message = message.replace(" ", ""); + len = message.length() / 2 + message.length() % 2; + getbytes = new byte[len]; + for (int i = 0; i < len; i++) { + String temp = message.substring(i * 2, i * 2 + 2); + getbytes[i] = (byte) Integer.parseInt(temp, 16); + } + + dos.write(getbytes); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + }; + threadPool.execute(terminal, 0, thread); + } + + private class syncTask implements Callable { + + private String message = ""; + + public syncTask(String message) { + super(); + this.message = message; + } + + public Integer call() throws Exception { + String ipadd = gprsIp; + int port = gprsPort; + // if (ruletype.equals("0001")) // Lon16 + // { + // ipString = gprsIpLon; + // port = gprsPortLon; + // } + + // state 为 0 表示正确应答,非0 为否定应答 + int state = 0; + String cmdreturn = ""; + + Socket socket = null; + // 获得对应socket的输入/输出流 + InputStream is = null; + OutputStream os = null; + // 建立数据流 + DataInputStream dis = null; + DataOutputStream dos = null; + + try { + socket = new Socket(ipadd, port); + } catch (Exception e) {// socket连接失败 + state = 4;// GPRS服务器连接失败 + return state; + } + + try { + socket.setSoTimeout(gprsTimeOut);// 设置超时时间 + // 获得对应socket的输入/输出流 + is = socket.getInputStream(); + os = socket.getOutputStream(); + // 建立数据流 + dis = new DataInputStream(is); + dos = new DataOutputStream(os); + + byte[] getbytes; + int len; + + message = message.replace("-", ""); + len = message.length() / 2 + message.length() % 2; + getbytes = new byte[len]; + for (int i = 0; i < len; i++) { + String temp = message.substring(i * 2, i * 2 + 2); + getbytes[i] = (byte) Integer.parseInt(temp, 16); + } + + dos.write(getbytes); + + // 从服务器获取数据 + int num = 0;// buffer中的数据长度 + byte[] readbuffer = new byte[1024]; + num = dis.read(readbuffer); + // 报文头是68--3761协议指令 + if (readbuffer[0] == 0x68) { + cmdreturn = Common.GetHexStr(readbuffer, num); + cmdreturn = cmdreturn.substring(0, cmdreturn.length() - 1); + + String temp[] = cmdreturn.split("-"); + // 获取功能码,非 FD 为否定应答 + if (temp[12].equals("FD")) { + state = 0; + } else { + state = 1; + } + } else { + state = 1; + } + } catch (Exception e) { + state = 3; + } + return state; + } + + } + + /** 线程检索 */ + public void RunScanThread() { + threadPool.scanthread(Work.language); + } + + /* 删除补抄结束的未抄读成功记录 */ + public static void Deltempmeters() { + + deleteruncount++; + if (deleteruncount < deleterunmax) + return; + deleteruncount = 0; + + // 删除 + String strsql = "delete from tempmeters where count>=" + powercount; + SQLHelper.ExecSql(strsql); + + // 删除昨天的抄表命令(LON16 日冻结数据不安全,只能抄读当前) + // 国网删除 删前天的抄表命令 + strsql = "delete from tempmeters WHERE (substring(wtime,1,10) <= convert(VARCHAR(10),getdate()-1,121) and protocol='0001' )" + + " or (substring(wtime,1,10) <= convert(VARCHAR(10),getdate()-2,121) and protocol<>'0001')"; + SQLHelper.ExecSql(strsql); + + // strsql = + // "delete from tempmeters WHERE substring(wtime,1,10) <= + // convert(VARCHAR(10),getdate()-2,121) and protocol<>'0001'"; + // SQLHelper.ExecSql(strsql); + } + + // 补抄处理 lon16 + private void ReDo(String batchtime) { + + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->Run"); + String tcomid = ""; + String comtype = ""; + String protocol = "0001";// 协议类型 + String cmdcode = ""; + String runTime = ""; + String strtd = ""; + String idString = ""; + int intervalTimming = 0; + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + format.setTimeZone(TimeZone.getTimeZone("GMT+8")); + String strsql = "select id,terminal, commodel,code,td,intervalTiming,protocol,id from tempmeters where count<" + + powercount + " and runTime<'" + batchtime + "' order by terminal"; + ResultSet rSet = SQLHelper.getResultSet(strsql); + // Log.writelog(clazzName,"ReDoByLon16()->sql:" + strsql); + if (rSet == null) { + return; + } + try { + while (rSet.next()) { + idString = rSet.getString("id"); + tcomid = rSet.getString("terminal"); + comtype = rSet.getString("commodel"); + cmdcode = rSet.getString("code"); + intervalTimming = rSet.getInt("intervalTiming"); + strtd = rSet.getString("td"); + protocol = rSet.getString("protocol"); + idString = rSet.getString("id"); + Log.writelog(Work.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->:" + tcomid + + " " + cmdcode + " " + strtd + " " + protocol); + // 进行补抄 + + if (!protocol.trim().equals("0001")) // 国网 + { + String binarypfc = "00000000" + Common.inttobinary(PFC); + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = tcomid.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + cmdcode = gw3761.create3761("6B", adomain, "0D", seqdomain, cmdcode); + } + + WriteData(comtype, tcomid, cmdcode, protocol, "", 0, strtd, "0", idString); + + // 更新下一次运行时间,以及补抄运行次数 + String[] arrayHM = batchtime.substring(11).split(":"); + Calendar calendar = Calendar.getInstance(); + calendar.set(0, 0, 0, Integer.parseInt(arrayHM[0].trim()), Integer.parseInt(arrayHM[1].trim())); + calendar.add(Calendar.MINUTE, intervalTimming); + runTime = format.format(calendar.getTime()); + runTime = Common.getDateStr7() + " " + runTime + ":00"; + String updateSql = "update tempmeters set count=count+1,runtime='" + runTime + "'" + " where id=" + + idString; + SQLHelper.ExecSql(updateSql); + + // 删除昨天的抄表数据 + } + } catch (SQLException e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + + try { + Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR1:" + e.getMessage()); + } + } + + /** + * 添加任务到队列 + * + * @param comtype + * 通道类型 0001串口 0002GPRS + * @param tcomid + * 集中器通信地址 + * @param cmdcode + * 下行命令 + * @param protocol + * 协议类型 0001旧规约 0002新规约 + * @param afncode + * 功能码 为空时可能是日冻结定采数据 + * @param Fn + * 测量点号 + * @param batchtime + * 抄读批次 + * @param responsetype + * 接收标志 + * @param batchtime + * 定采时的数据时标 + * @param idString + * 补抄表中的ID + */ + private void WriteData(String comtype, String tcomid, String cmdcode, String protocol, String afncode, int Fn, + String batchtime, String responsetype, String idString) { + + if (comtype.equals("0001")) {// 串口 + try { + while (serial.isOpen) { + Thread.sleep(1000); + if (!serial.isOpen) { + break; + } + } + + serial.init(); + if (protocol.equals("0001")) { + serial.start(0);// 旧协议,无校验位 + } else { + serial.start(2);// 新协议,偶校验位 + } + serial.writeComm(0, tcomid, cmdcode, protocol, afncode, Fn, comTimeOut, batchtime, responsetype, + idString); + // serial.close(); + } catch (Exception e) { + Log.writelog(Work.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } else {// GPRS + addTask(protocol, tcomid, cmdcode, 0, afncode, Fn, "", batchtime, responsetype, idString); + } + } + + private boolean bRunEleAnalyzer = false; + + /** 根据协议解析上报事件数据 */ + public void RunEleAnalyzerData() { + if (bRunEleAnalyzer == true) + return; + // Log.writelog(Work.clazzName, + // Thread.currentThread().getStackTrace()[1].getMethodName() + // + "->Run "); + Reconnect();/* 连接数据库 */ + // System.out.println("\n上报事件:"); + String strsql = "select eventid,wtime,content,ruletype from eventdata where status='0' order by wtime desc"; + Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql);/* 查询数据库是否存在0E上报事件 */ + if (rSet == null) { + return; + } + // if (!rSet.next()) { + // return; + // } + bRunEleAnalyzer = true; + // Log.writelog(Work.clazzName, + // Thread.currentThread().getStackTrace()[1].getMethodName() + // + "->strat "); + try { + while (rSet.next()) { + if (SQLHelper.isclose == true) {// 连接关闭后退出 + break; + } + Log.writelog(Work.clazzName, "EleAnalyzerData->start " + rSet.getString("wtime")); + + // 根据协议解析事件上报数据,并发送短信息,写入 EventInfo 表 + EleAnalyzerData(rSet.getInt("EventID"), rSet.getString("wtime"), rSet.getString("content"), + rSet.getString("RuleType")); + Log.writelog(Work.clazzName, "EleAnalyzerData->over " + rSet.getString("wtime")); + } + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + e.getMessage()); + } + bRunEleAnalyzer = false; + } + + /** + * 根据协议解析事件上报数据,并发送短信息 + * + * @param eventid + * 事件ID + * @param time + * 上报时间 + * @param datas + * 完整报文 + * @param ruletype + * 协议类型 0001为旧协议,0002为新协议 (未使用) + */ + public static void EleAnalyzerData(int eventid, String time, String datas, String ruletype) { + if (datas.length() > 0) { + // Log.writelog(Work.clazzName, "gw3761.AnalyzerData->start"); + gw3761.AnalyzerData(eventid, time, datas); + // Log.writelog(Work.clazzName, "gw3761.AnalyzerData->over"); + // if (ruletype.equals("0001")) { + // // lampold.AnalyzerData(eventid, time, datas); + // } else { + // // gw3761.AnalyzerData(eventid, time, datas); + // } + } + // 更新EventData处理状态 + Protocol.ModifyEventData(eventid); + } + + /** 清空连接 */ + public synchronized static void Reconnect() { + if (SQLHelper.isclose == true) { + SQLHelper.closeconn(); + } + } +} diff --git a/selfDevelop/src/main/java/com/back/communication/CmdObject485.java b/selfDevelop/src/main/java/com/back/communication/CmdObject485.java new file mode 100644 index 0000000..faecda4 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/CmdObject485.java @@ -0,0 +1,30 @@ +package com.back.communication; + +public class CmdObject485 { + public int cmdid; + public String terminal; + public String outdata; + public String ruletype; + private String afncode; + private int Fn; + public int timeout; + public String batchtime; + public String responsetype; + public String taskidString; + + public CmdObject485(int cmdid, String terminal, String outdata, + String ruletype, String afncode, int Fn, int timeout, + String batchtime, String responsetype, String taskidString) { + this.cmdid = cmdid; + this.terminal = terminal; + this.outdata = outdata; + this.ruletype = ruletype; + this.afncode = afncode; + this.Fn = Fn; + this.timeout = timeout; + this.batchtime = batchtime; + this.responsetype = responsetype; + this.taskidString = taskidString; + + } +} diff --git a/selfDevelop/src/main/java/com/back/communication/SendSMS.java b/selfDevelop/src/main/java/com/back/communication/SendSMS.java new file mode 100644 index 0000000..7d6ac4f --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SendSMS.java @@ -0,0 +1,266 @@ +package com.back.communication; + +import jssc.SerialPort; +import jssc.SerialPortException; + +public class SendSMS { + private String msgCenterPhone; + private String portName; + private int baud; + private int parity; + private int stop; + private int data; + private int gsmType; + private SerialPort serialPort; + /** AT+CMGS= */ + public final static byte[] SMS_STRUCTOR = { 0x41, 0x54, 0x2B, 0x43, 0x4D, 0x47, 0x53, 0x3D }; + /** AT+CMGF=0 */ + public final static byte[] SMS_PDU_HEADER = { 0x41, 0x54, 0x2B, 0x43, 0x4D, 0x47, 0x46, 0x3D, + 0x30 }; + public final static byte[] SMS_HEADER_START = { 0x41, 0x54, 0x2B, 0x43, 0x4D, 0x47, 0x53, 0x3D }; + public final static byte[] SMS_HEADER_END = { 0x0D }; + public final static byte[] SMS_CONTENT_END = { 0x1A }; + + public void setCenterPhone(String phoneNumber) { + this.msgCenterPhone = phoneNumber; + } + + public void setSerialPort(String portName) { + this.portName = portName; + } + + public void setParams(int baudRate, int parity, int stop, int data) { + this.baud = baudRate; + this.parity = parity; + this.stop = stop; + this.data = data; + } + + public void setGSMType(int gsmType) { + this.gsmType = gsmType; + } + + public SendSMS() { + // msgCenterPhone = msgCenterPhone.trim(); + portName = "COM20"; + baud = 115200; + parity = 0; + stop = 1; + data = 8; + gsmType = 2; + } + + public SendSMS(String phoneNo, String portName, int gsmType) { + msgCenterPhone = phoneNo; + this.portName = portName; + baud = 115200; + parity = 0; + stop = 1; + data = 8; + this.gsmType = gsmType; + } + + /** + * 确认发送格式并发送短信,将长短信分为N条正常短信 + * + * @param mobileSendAlarmInfo + * @return 1:发送成功;-1:发送失败 + */ + public int sendSMS(String destPhone, String content) { + /** + * 发送成功标志 + */ + int succeedFlag = 0; + serialPort = new SerialPort(this.portName); + try { + System.out.println("Port opened:" + serialPort.openPort()); + System.out.println("Params setted:" + serialPort.setParams(115200, 8, 1, 0)); + System.out.println("Send PDU Header" + serialPort.writeBytes(SMS_PDU_HEADER)); + System.out.println("Send Header End" + serialPort.writeBytes(SMS_HEADER_END)); + int timeout = 0; + while (true) { + Thread.sleep(100); + byte[] b = new byte[21]; + b = serialPort.readBytes(); + if (timeout > 50) { + System.out.println("Time Out"); + return succeedFlag = -1; + } + if (b == null) { + timeout++; + continue; + } + String s = new String(b); + if (s.indexOf("OK") != -1) { // 'OK' + System.out.println("Set PDU Successful!"); + break; + } + } + int[] tpduLength = new int[1]; + String pack = packStrMessage(destPhone, content, msgCenterPhone, tpduLength); + System.out.println("Send Header Start" + serialPort.writeBytes(SMS_HEADER_START)); + String strLength = (tpduLength[0] < 100 ? ("0" + Integer.toString(tpduLength[0])) : Integer + .toString(tpduLength[0])); + System.out.println("Send Header Length" + serialPort.writeBytes(strLength.getBytes())); + System.out.println("Send Header End" + serialPort.writeBytes(SMS_HEADER_END)); + Thread.sleep(100); + timeout = 0; + while (true) { + Thread.sleep(100); + byte[] b = new byte[21]; + b = serialPort.readBytes(); + + if (timeout > 50) { + System.out.println("Time Out"); + return succeedFlag = -1; + } + if (b == null) { + timeout++; + continue; + } + String s = new String(b); + if (s.indexOf('>') != -1) { // '>' + System.out.println("Title Successful!"); + break; + } + if (s.indexOf("ERROR") != -1) { // 'R' + System.out.println("Error"); + return succeedFlag = -1; + } + } + System.out.println("Send Content: " + serialPort.writeBytes(pack.getBytes())); + System.out.println("Send Contend End: " + serialPort.writeBytes(SMS_CONTENT_END)); + System.out.println("Send Header End: " + serialPort.writeBytes(SMS_HEADER_END)); + timeout = 0; + while (true) { + Thread.sleep(100); + byte[] b = new byte[21]; + b = serialPort.readBytes(); + if (timeout > 50) { + System.out.println("Time Out"); + return succeedFlag = -1; + } + if (b == null) { + timeout++; + continue; + } + String s = new String(b); + System.out.println(s); + // System.exit(0); + // serialPort.closePort(); + if (s.indexOf("OK") != -1) { // '>' + System.out.println("Content Successful!"); + serialPort.closePort(); + return succeedFlag = 1; + } + if (s.indexOf("ERROR") != -1) { // 'R' + System.out.println("Error"); + serialPort.closePort(); + return succeedFlag = -1; + } + serialPort.closePort(); + } + } catch (SerialPortException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return succeedFlag; + } + + private String packStrMessage(String destPhone, String content, String centerPhone, + int[] tpduLength) { + if (destPhone == null || content == null || centerPhone == null) + return ""; + // encode the SCA + byte[] sca = new byte[3]; + sca[0] = (byte) (0x00); + sca[1] = (byte) 0x11; + sca[2] = (byte) 0x00; + // encode TPDU + if (!destPhone.startsWith("86")) // add china code 86 to dest phone. 81 为日本的代码 + destPhone = "86" + destPhone; + int length; + int destLength = length = destPhone.length(); + if (length % 2 != 0) { // if the dest code is odd , then add 'F' + destPhone += "F"; + length++; + } + // content += new String( new char[]{ 0x00 } ); + char[] ccontent = content.toCharArray(); + int contentLength = ccontent.length; + /* + * Data Length Dest Phone(encoding) | Data(encoding) _________|__________ | _____|________ The + * tpdu' sample byte 11 00 0D 91 68 31 19 01 28 14 F1 00 00 00 05 D4 E2 94 0A 02 | | | | | | | | + * | | TON/NPI | | VP Validity Period | | Dest Phone Length(Number) | DCS Data Coding + * Scheme(00-ASCII , 08-UCS2) | MR Message Reference PID Protocol ID 8 Bits + * MTI,RD,VPF,SRR,UDHI,RP,MMS,SRI so 4 + phoneLength / 2 + 3 + 1 + contenLength is the tpdu + * length + */ + byte[] tpdu = new byte[2 + length / 2 + 3 + 1 + contentLength * 2]; + int index = 0; + tpdu[index++] = (byte) destLength; + tpdu[index++] = (byte) 0x91; + for (int i = 0; i < length; i += 2) { + tpdu[index++] = swap(destPhone.substring(i, i + 2), 16); + } + tpdu[index++] = 0x00; + tpdu[index++] = 0x08; // UCS2 + tpdu[index++] = (byte) 0xA7; + tpdu[index++] = (byte) (contentLength * 2); + for (int i = 0; i < contentLength; i++) { + if (i < ccontent.length) { + tpdu[index++] = (byte) (ccontent[i] >> 8); + tpdu[index++] = (byte) (ccontent[i] & 0x00FF); + } else { + tpdu[index++] = (byte) (0xFF); + tpdu[index++] = (byte) (0xFF); + } + } + // copy sca and tpdu to ret + int scaLength = sca.length; + tpduLength[0] = tpdu.length + 2; + byte[] ret = new byte[scaLength + tpdu.length]; + System.arraycopy(sca, 0, ret, 0, scaLength); + System.arraycopy(tpdu, 0, ret, scaLength, tpdu.length); + String r = new String(); + for (int i = 0; i < ret.length; i++) { + String s = Integer.toHexString((char) ret[i] & 0x00ff); + if (s.length() == 1) + s = "0" + s; + r += s; + } + // System.out.println( r ); + return r; + } + + // swap the string and parse it as specail radix byte,just same binary code. + // note: the s must has two length string. + // eg. swap( "12" , 16 ) will return byte 33 + // eg. swap( "68" , 16 ) will return byte -122 + public static byte swap(String s, int radix) { + byte b1 = Byte.parseByte(s.substring(0, 1), radix); + byte b2 = Byte.parseByte(s.substring(1, 2), radix); + return (byte) (b2 * radix + b1); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("The SMS Properties:\n"); + sb.append("\nSerial Port=" + serialPort); + sb.append("\nBaud=" + baud); + sb.append("\nData Bits=" + data); + sb.append("\nStop Bit=" + stop); + sb.append("\nParity=" + parity); + sb.append("\nSMS Center Phone=" + msgCenterPhone); + return sb.toString(); + } + /* + public static void mai1n(String[] args) { + SendSMS sender = new SendSMS("13800210500", "COM20", 2);// SIM卡所在地短信中心号码、端口号、SIM卡类型默认2即可 + int code = sender.sendSMS("18666665078", "Just for a test");// 接收号码、内容 + System.out.println(code); + }*/ +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/communication/SerialComm.java b/selfDevelop/src/main/java/com/back/communication/SerialComm.java new file mode 100644 index 0000000..70097c2 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SerialComm.java @@ -0,0 +1,337 @@ +package com.back.communication; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Date; +import java.util.TooManyListenersException; + +//import javax.comm.CommPortIdentifier; +//import javax.comm.SerialPort; +//import javax.comm.SerialPortEvent; +//import javax.comm.SerialPortEventListener; +import com.back.common.Common; +import gnu.io.*; + + +import com.back.action.Log; +import com.back.protocol.GW3761; +import com.back.protocol.Lon16; + +public class SerialComm implements SerialPortEventListener { + + public final static String PORT_OWER = "App"; + + private String portName; + + private CommPortIdentifier portId; + + private SerialPort serialPort; + + private DataInputStream inputStream; + + private OutputStream outputStream; + + private Object readWriteLock = new Object(); + + private Lon16 lon16 = new Lon16(); + + private GW3761 gw3761 = new GW3761(); + + private String clazzName = new Object() { + public String getClassName() + { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + Boolean isread = false; + String afncode = ""; + Date wdate;// 写指令时间 + int cmdid = 0; + String wterminal = "";// 写指令地址 + String rterminal = "";// 读指令地址 + String protocol = "";// 协议类型 + int Fn = 0;// 功能码 + String batchtime = "";// 定采批次时间 + String describe =""; //任务描述 + String outdata = ""; //设置时命令 + String taskidString ="";//定采任务号 + + public boolean isOpen; + + public boolean isStart; + + public static SerialComm Instance; + + public static SerialComm getInstance(String port) { + if (Instance == null) { + Instance = new SerialComm(port); + } + return Instance; + } + + private SerialComm(String port) { + isOpen = false; + isStart = false; + + portName = port; + } + + public void init() { + if (isOpen) { + close(); + } + + try { + // 根据传入的串口名创建串口标识 + portId = CommPortIdentifier.getPortIdentifier(portName); + + // 打开串口并返回串口对象 + serialPort = (SerialPort) portId.open(PORT_OWER, 2000); + + // 通过串口对象获得输入流 + inputStream = new DataInputStream(serialPort.getInputStream()); + + // 通过串口对象获得输出流 + outputStream = serialPort.getOutputStream(); + + isOpen = true; + } catch (Exception ex) { + isOpen = false; + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->" + ex.getMessage()); + } + } + + /** + * 启动串口 + * + * @param flag + * 0为无校验 1为奇校验 2为偶校验 + */ + public void start(int flag) throws Exception { + if (!isOpen) { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Com " + portName + "is Oppen"); + return; + } + + try{ + // 设置串口监听对象 + serialPort.addEventListener(this); + + // 设置串口数据可用 + serialPort.notifyOnDataAvailable(true); + + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->addEventListener OK!" ); + }catch (TooManyListenersException e) { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + e.getMessage()); + } + + + switch (flag) { + case 0: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); + break; + case 1: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_ODD); + break; + case 2: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); + break; + } + isStart = true; + } + + public void stop() { + if (isStart) { + // 设置串口数据是否可用 + serialPort.notifyOnDataAvailable(false); + + // 移除串口监听事件 + serialPort.removeEventListener(); + + isStart = false; + } + } + + public void close() { + stop(); + + if (isOpen) { + try { + // 关闭流对象与串口对象 + inputStream.close(); + outputStream.close(); + serialPort.close(); + serialPort = null; + + isOpen = false; + } catch (IOException ex) { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->" + ex.getMessage()); + } + } + } + + public void serialEvent(SerialPortEvent event) { + switch (event.getEventType()) { + case SerialPortEvent.BI: + case SerialPortEvent.OE: + case SerialPortEvent.FE: + case SerialPortEvent.PE: + case SerialPortEvent.CD: + case SerialPortEvent.CTS: + case SerialPortEvent.DSR: + case SerialPortEvent.RI: + case SerialPortEvent.OUTPUT_BUFFER_EMPTY: + break; + case SerialPortEvent.DATA_AVAILABLE: + //System.out.println("SerialComm->serialEvent : DATA_AVAILABLE"); + // 从串口获得数据,获取的数据以流的形式读取 + readComm(); + break; + default: + break; + } + } + + /** + * 写指令到串口 + * + * @param cmdid + * 指令ID + * @param terminal + * 集中器通信地址 + * @param outdata + * 下行报文 + * @param ruletype + * 协议类型 + * @param afncode + * 电表抄读用到 + * @param timeout + * 超时时间 + * @throws InterruptedException + */ + public synchronized void writeComm(int cmdid, String terminal, String outdata, String ruletype, String afncode, int Fn, int timeout, String batchtime, String responsetype,String taskidString) throws InterruptedException { + synchronized (readWriteLock) { + this.afncode = afncode; + this.wdate = Common.getcurdate(); + this.cmdid = cmdid; + this.wterminal = terminal; + this.rterminal = terminal; + this.protocol = ruletype; + this.Fn = Fn; + this.batchtime = batchtime; + this. describe = ""; + this.outdata = outdata; + this.taskidString = taskidString; + + if (cmdid==0) + { + describe = "[Read Meter Tasks]";//抄表任务 + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + "]Write Comm Send:" + describe ); + } + + try { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + "]Write Comm Send:" + outdata); + outdata = outdata.replaceAll("-", ""); + + if (outdata.length() > 0) { + int len; + byte[] getbytes; + if (ruletype.equals("0001")) + { + len = outdata.length(); + getbytes = new byte[len + 1]; + byte[] dataByte = outdata.getBytes(); + for(int i=0;i[" + terminal + "]Read Comm数据超时"); + } + close();// 关闭串口 + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + "]Read Comm 关闭"); + } + } catch (IOException ex) { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Error:" + ex.getMessage()); + } + } + } + + /** 用流读取数据,写事件表和写结果表 */ + public void readComm() { + int num = 0;// buffer中的数据长度 + String receivedata = "";// 串口接收数据 + byte[] readbuffer = new byte[1024]; + byte[] buffer = new byte[1024]; + int index = 0; + try { + Date cdate = Common.getcurdate(); //字节超时 + Date wdate = Common.getcurdate(); + long datediff = 0; + while (datediff < 80) { + if (inputStream.available() > 0) { + num = inputStream.read(readbuffer); + System.arraycopy(readbuffer, 0, buffer, index, num); + index += num; + wdate = Common.getcurdate(); + } + cdate = Common.getcurdate(); + datediff = cdate.getTime() - wdate.getTime(); + } + + } catch (IOException e) { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + return; + } + receivedata += Common.GetHexStr(buffer, index); + if (buffer[0]!=0x68) + { + receivedata = receivedata.replace("-", "").replace("0D0A", ""); + receivedata = Common.HexStr2AsciiStr(receivedata); + } + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->Read Data:" + receivedata); + + isread = true; + if (protocol.equals("0001")) {// 旧协议 + lon16.ResolvingData(cmdid,this.outdata, rterminal, receivedata, 0, "0001", batchtime,taskidString); + } else {// 新协议 + gw3761.ResolvingData(cmdid, rterminal, receivedata, 0, "0001", afncode, Fn, batchtime, taskidString,this.outdata); + } + + } +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/communication/SerialComm485.java b/selfDevelop/src/main/java/com/back/communication/SerialComm485.java new file mode 100644 index 0000000..0b81387 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SerialComm485.java @@ -0,0 +1,1063 @@ +package com.back.communication; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.sql.ResultSet; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.TooManyListenersException; + +//import javax.comm.CommPortIdentifier; +//import javax.comm.SerialPort; +//import javax.comm.SerialPortEvent; +//import javax.comm.SerialPortEventListener; +import com.back.common.Common; +import gnu.io.*; + +import com.back.action.Log; +import com.back.jdbc.SQLHelper; +import com.back.protocol.GW3761; +import com.back.protocol.Lon16; + +/** + * 485总线集中器处理流程处理 + * + * @author Administrator + * + */ +public class SerialComm485 implements SerialPortEventListener { + + public static int beat485;// 485集中器跳时间 (毫秒) + public static int comTimeOut485;// 集中器连接串口(毫秒) + public final static String PORT_OWER = "App"; + + private LinkedList cmdQueue; // 命令处理队列 + private List termina485lList; // 485集中器队列 + String receivedata = "";// 串口接收数据 + private String portName; + private int msg[] = new int[2024]; + private int readMsg[] = new int[2024]; // 接收缓存 + private int readMsgCount = 0; // 接收到的字节数 + + private CommPortIdentifier portId; + private boolean pCmd = false; + private SerialPort serialPort; + + private DataInputStream inputStream; + + private OutputStream outputStream; + + private Object readWriteLock = new Object(); + + private Lon16 lon16 = new Lon16(); + + private GW3761 gw3761 = new GW3761(); + + private String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + Boolean isread = false; + String afncode = ""; + Date wdate;// 写指令时间 + int cmdid = 0; + String wterminal = "";// 写指令地址 + String rterminal = "";// 读指令地址 + String protocol = "";// 协议类型 + int Fn = 0;// 功能码 + String batchtime = "";// 定采批次时间 + String describe = ""; // 任务描述 + String outdata = ""; // 设置时命令 + String taskidString = "";// 定采任务号 + + public boolean isOpen; // 打开 + + public boolean isStart;// 开启接收事备 + + public static SerialComm485 Instance; + + public static SerialComm485 getInstance(String port) { + if (Instance == null) { + Instance = new SerialComm485(port); + } + return Instance; + } + + private SerialComm485(String port) { + isOpen = false; + isStart = false; + + portName = port; + cmdQueue = new LinkedList(); // 创建工作队列 + + termina485lList = new ArrayList(); + } + + /** + * 485总线任务 + * + * @throws InterruptedException + */ + public void RS485Bus_Task() throws InterruptedException { + // 获取485集中器 + String strsql = "SELECT comid FROM terminals WHERE terminals.ComModel='0003'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + termina485lList.clear(); + // 获取485集中器通信地址 + try { + while (rSet.next()) { + termina485lList.add(rSet.getString("comid")); + } + + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Load terminal 485 ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Close ERROR:" + e.getMessage()); + } + String comidString = ""; + int count = 0; + int tCount = termina485lList.size(); + // 事件轮巡时间 3S + int iMax = beat485 / 100 / tCount; + if (iMax < 1) + iMax = 1; + + try { + init(); + start(0); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // 485集中器轮巡处理 + if (isStart) // 接收事件开启时,才能处理 + while (termina485lList.size() > 0) { + + if (cmdQueue.size() > 0) // 页面任务 + { // 转发命令处理 + CmdObject485 cmdObject485 = cmdQueue.get(0); + cmdQueue.remove(0); + + pCmd = true; + writeComm(cmdObject485.cmdid, cmdObject485.terminal, + cmdObject485.outdata, cmdObject485.ruletype, "", 0, + comTimeOut485, "", cmdObject485.responsetype, ""); + + // 如何判断完成 + if (!isread) {// 超时处理 + gw3761.ResolvingData(cmdid, rterminal, "", 3, "0001", + afncode, Fn, batchtime, taskidString, + this.outdata); + Log.writelog(clazzName, Thread.currentThread() + .getStackTrace()[1].getMethodName() + + "->[" + + cmdObject485.cmdid + "]Read Comm OutTime"); + } + + // 清除相应集中器 + int i = termina485lList.indexOf(cmdObject485.cmdid); + if (i > -1) + termina485lList.remove(i); + + continue; + } + count++; + Thread.sleep(100); + // 如果此处理轮巡周期长的话, + + if (count < iMax) { + continue; + } + pCmd = false; + count = 0; + comidString = termina485lList.get(0); + termina485lList.remove(0); + // 轮巡任务处理**************************************** + try { + BeatTask(comidString); + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread() + .getStackTrace()[1].getMethodName() + + "->[" + + comidString + "]BeatTask Error:" + e.getMessage()); + } + + }// termina485lList.size() > 0 + close(); + } + + /** + * 更新485集中器状态 + * + * @param comidString + * @param onLineSate + */ + private void UpdateTerminalOnLineState(String comidString, + boolean onLineSate) { + String sql = ""; + if (onLineSate) + sql = "update terminals set onlinestate=1,onlinetime='" + + Common.getDateStr0() + "'" + "where comid='" + + comidString + "'"; + else + sql = "update terminals set onlinestate=0,onlinetime='" + + Common.getDateStr0() + "'" + "where comid='" + + comidString + "'"; + SQLHelper.ExecSql(sql); + } + + /** + * 校时处理 + */ + private boolean CheckTime(String comidString) { + // 获取报文中时间 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + String tempString = "20" + Integer.toHexString(readMsg[23]) + "-" + + Integer.toHexString(readMsg[22] & 0x3F) + "-" + + Integer.toHexString(readMsg[21]) + " " + + Integer.toHexString(readMsg[20]) + ":" + + Integer.toHexString(readMsg[19]) + ":" + + Integer.toHexString(readMsg[18]); + try { + Date date = sdf.parse(tempString); + // 计算时差 + long diff = (new Date()).getTime() - date.getTime(); + long minute = diff / (60 * 1000); + if (minute > 5) { + SendCMDCheckTime(comidString); + } + } catch (ParseException e) { + // TODO Auto-generated catch block + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Time Msg Error:" + + this.receivedata); + return false; + } + return true; + } + + /** + * 发送校时命令 A5 F31 对时命令 + * + * @param comidString + */ + private void SendCMDCheckTime(String comidString) { + Date date = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yy MM dd HH mm ss"); + String[] time = format.format(date).split(" "); + + String strMsgString = "00 00 40 03 " + time[5] + " " + time[4] + " " + + time[3] + " " + time[2] + " " + time[1] + " " + time[0]; + SendCmd(comidString, "A5", strMsgString); + if (!isread) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Check Clock Out Time!"); + return; + } + } + + /** + * 读取事件 + * + * @param comidString + */ + private void ReadEvent(String comidString) { + int control = readMsg[6]; + // 无事件标识 + if ((control & 0x20) == 0) + return; + // 确信EC的位置 + int seq = readMsg[13]; + int ec = 0; + int dbec = 0; + if ((seq & 0x80) > 0) { + ec = readMsg[readMsgCount - 10]; + } else { + ec = readMsg[readMsgCount - 4]; + } + + // 加载数据库 重要事件 计数器 + String strsql = "select ec from terminals where comid='" + comidString + + "'"; + + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + try { + while (rSet.next()) { + ec = rSet.getInt("ec"); + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Get Ec from DataBase ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Close ERROR:" + e.getMessage()); + } + + if (dbec!=ec) + return; + int y =0; + + y= ec- dbec; + if (ec20) + ec = (dbec + 20) & 0xFF; + //读事件 只读一条 + String strMsgString = "00 00 01 00 " + Common.dec2Hex(dbec,2) + " " + Common.dec2Hex(ec,2); + + pCmd = true; + SendCmd(comidString, "0E", strMsgString); + + + //更新数据库中记数器 + strsql = "update temrinals set ec=" + String.valueOf(ec) + " where comid='" + comidString + + "'"; + SQLHelper.ExecSql(strsql); + + } + + /* + * 命令是否合法 + */ + private boolean CheckMsg(String comidString) { + if (readMsgCount < 20) // 长度不足 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Length Error:" + + this.receivedata); + return false; + } + if (readMsg[0] != 0x68) // 第一个字节不是68 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]First Byte Not 68 Error:" + + this.receivedata); + return false; + } + if (readMsg[1] != readMsg[3] || readMsg[2] != readMsg[4]) // 两个长度不对 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Length Byte Error:" + + this.receivedata); + return false; + } + + // 报文长度 + int temp = (readMsg[1] + (readMsg[2] << 8)) >> 2 + 8; + if (temp != readMsgCount) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Msg Length Error:" + + this.receivedata); + return false; + } + + // 计算校验和 + int iCS = 0; + for (int i = 6; i < readMsgCount; i++) { + iCS = iCS + readMsg[i]; + } + iCS = iCS & 0xFF; + + if (iCS != readMsg[readMsgCount - 2]) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]CS Error:" + + this.receivedata); + return false; + } + + // 通信地址 不对应 + String comid = Integer.toHexString(readMsg[8]) + + Integer.toHexString(readMsg[7]) + + Integer.toHexString(readMsg[10]) + + Integer.toHexString(readMsg[9]); + if (comid.equals(comidString) == false) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Comid Error:" + + this.receivedata); + return false; + } + return true; + } + + private void BeatTask(String comidString) { + // 下发读取时钟命令 AC 00 00 01 00 + SendCmd(comidString, "AC", "00 00 01 00"); + UpdateTerminalOnLineState(comidString, isread); + if (!isread) {// 不在线 + // 更新集中器在线状态 + return; + } + if (this.receivedata.trim().equals("")) + return; + + try { + if (CheckMsg(comidString) == false)// 没有通过数据校验 + { + return; + } + // 校时处理 + CheckTime(comidString); + // 事件读取 + ReadEvent(comidString); + } catch (Exception e) { + // TODO: handle exception + } + + } + + /** + * 下发集中器命令 + * + * @param terminalComid + * @param Afn + * @param Data + */ + private void SendCmd(String terminalComid, String Afn, String Data) { + cmdinfor.Create(Afn, terminalComid, Data, GetPFC(), false); + String outdata = GetSendCmd(cmdinfor); + try { + writeComm(-1, terminalComid, outdata, "0002", "", 0, 3000, "", "1", + ""); + } catch (InterruptedException e) { + } + } + + /** + * 添加到485总线命令队列中 + * + * @param cmdid + * 命令ID + * @param terminal + * 集中器通信地址 + * @param outdata + * 下发命令 + * @param ruletype + * 协议类型 + * @param afncode + * afn代码 + * @param Fn + * fn代码 + * @param timeout + * 超时时间 + * @param batchtime + * 批量任务生成时间 + * @param responsetype + * 是否需要返回 + * @param taskidString + * 线程号 + */ + public void addTask(int cmdid, String terminal, String outdata, + String ruletype, String afncode, int Fn, int timeout, + String batchtime, String responsetype, String taskidString) { + cmdQueue.add(new CmdObject485(cmdid, terminal, outdata, ruletype, + afncode, Fn, timeout, batchtime, responsetype, taskidString)); + } + + public void init() { + if (isOpen) { + close(); + } + + try { + // 根据传入的串口名创建串口标识 + portId = CommPortIdentifier.getPortIdentifier(portName); + + // 打开串口并返回串口对象 + serialPort = (SerialPort) portId.open(PORT_OWER, 2000); + + // 通过串口对象获得输入流 + inputStream = new DataInputStream(serialPort.getInputStream()); + + // 通过串口对象获得输出流 + outputStream = serialPort.getOutputStream(); + + isOpen = true; + } catch (Exception ex) { + isOpen = false; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->" + ex.getMessage()); + } + } + + /** + * 启动串口 + * + * @param flag + * 0为无校验 1为奇校验 2为偶校验 + */ + public void start(int flag) throws Exception { + if (!isOpen) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Com " + portName + " is open!"); + return; + } + + try { + // 设置串口监听对象 + serialPort.addEventListener(this); + + // 设置串口数据可用 + serialPort.notifyOnDataAvailable(true); + + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->addEventListener OK!"); + } catch (TooManyListenersException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Error:" + e.getMessage()); + } + + switch (flag) { + case 0: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, + SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); + break; + case 1: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, + SerialPort.STOPBITS_1, SerialPort.PARITY_ODD); + break; + case 2: + serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, + SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN); + break; + } + isStart = true; + } + + /** + * 关闭事件接收 + */ + public void stop() { + if (isStart) { + // 设置串口数据是否可用 + serialPort.notifyOnDataAvailable(false); + + // 移除串口监听事件 + serialPort.removeEventListener(); + + isStart = false; + } + } + + /** + * 关闭通信端口 + */ + public void close() { + stop(); + + if (isOpen) { + try { + // 关闭流对象与串口对象 + inputStream.close(); + outputStream.close(); + serialPort.close(); + serialPort = null; + + isOpen = false; + } catch (IOException ex) { + Log.writelog( + clazzName, + Thread.currentThread().getStackTrace()[1] + .getMethodName() + "->" + ex.getMessage()); + } + } + } + + public void serialEvent(SerialPortEvent event) { + switch (event.getEventType()) { + case SerialPortEvent.BI: + case SerialPortEvent.OE: + case SerialPortEvent.FE: + case SerialPortEvent.PE: + case SerialPortEvent.CD: + case SerialPortEvent.CTS: + case SerialPortEvent.DSR: + case SerialPortEvent.RI: + case SerialPortEvent.OUTPUT_BUFFER_EMPTY: + break; + case SerialPortEvent.DATA_AVAILABLE: + // System.out.println("SerialComm->serialEvent : DATA_AVAILABLE"); + // 从串口获得数据,获取的数据以流的形式读取 + readComm(); + break; + default: + break; + } + } + + /** + * 写指令到串口 + * + * @param cmdid + * 指令ID + * @param terminal + * 集中器通信地址 + * @param outdata + * 下行报文 + * @param ruletype + * 协议类型 + * @param afncode + * 电表抄读用到 + * @param timeout + * 超时时间 + * @throws InterruptedException + */ + public synchronized void writeComm(int cmdid, String terminal, + String outdata, String ruletype, String afncode, int Fn, + int timeout, String batchtime, String responsetype, + String taskidString) throws InterruptedException { + synchronized (readWriteLock) { + this.afncode = afncode; + this.wdate = Common.getcurdate(); + this.cmdid = cmdid; + this.wterminal = terminal; + this.rterminal = terminal; + this.protocol = ruletype; + this.Fn = Fn; + this.batchtime = batchtime; + this.describe = ""; + this.outdata = outdata; + this.taskidString = taskidString; + + if (cmdid == 0) { + describe = "Read Meter Tasks";//抄表任务 + Log.writelog( + clazzName, + Thread.currentThread().getStackTrace()[1] + .getMethodName() + + "->[" + + terminal + + "]Write Comm Send:" + describe); + } + + try { + Log.writelog( + clazzName, + Thread.currentThread().getStackTrace()[1] + .getMethodName() + + "->[" + + terminal + + "]Write Comm Send:" + outdata); + outdata = outdata.replaceAll("-", ""); + + if (outdata.length() > 0) { + int len; + byte[] getbytes; + if (ruletype.equals("0001")) { + len = outdata.length(); + getbytes = new byte[len + 1]; + byte[] dataByte = outdata.getBytes(); + for (int i = 0; i < len; i++) { + getbytes[i] = dataByte[i]; + } + getbytes[len] = (byte) 0x0d; + } else { + len = outdata.length() / 2 + outdata.length() % 2; + getbytes = new byte[len]; + for (int i = 0; i < len; i++) { + String temp = outdata.substring(i * 2, i * 2 + 2); + getbytes[i] = (byte) Integer.parseInt(temp, 16); + } + } + + isread = false; + outputStream.write(getbytes); + if (!responsetype.equals("1")) {// 增加需应答时处理2011-06-28 + long datediff = 0; + Date cdate = Common.getcurdate(); + while (datediff < timeout) { // 超时处理 + if (isread) + break; + cdate = Common.getcurdate(); + datediff = cdate.getTime() - wdate.getTime(); + Thread.sleep(50); + } + } + + } + } catch (IOException ex) { + Log.writelog( + clazzName, + Thread.currentThread().getStackTrace()[1] + .getMethodName() + "->Error:" + ex.getMessage()); + } + } + } + + /** 用流读取数据,写事件表和写结果表 */ + public void readComm() { + int num = 0;// buffer中的数据长度 + receivedata = "";// 串口接收数据 + byte[] readbuffer = new byte[1024]; + byte[] buffer = new byte[1024]; + int index = 0; + try { + Date cdate = Common.getcurdate(); // 字节超时 + Date wdate = Common.getcurdate(); + long datediff = 0; + while (datediff < 80) { + if (inputStream.available() > 0) { + num = inputStream.read(readbuffer); + System.arraycopy(readbuffer, 0, buffer, index, num); + index += num; + wdate = Common.getcurdate(); + } + cdate = Common.getcurdate(); + datediff = cdate.getTime() - wdate.getTime(); + } + + } catch (IOException e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.getMessage()); + return; + } + receivedata += Common.GetHexStr(buffer, index); + System.arraycopy(buffer, 0, readMsg, 0, index); + readMsgCount = index; + + if (buffer[0] != 0x68) { // Lon16 集中器 + receivedata = receivedata.replace("-", "").replace("0D0A", ""); + receivedata = Common.HexStr2AsciiStr(receivedata); + } + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Read Data:" + receivedata); + + isread = true; + if (pCmd == false) + return; + + // 页面命令处理 + if (protocol.equals("0001")) {// 旧协议 + lon16.ResolvingData(cmdid, this.outdata, rterminal, receivedata, 0, + "0001", batchtime, taskidString); + } else {// 新协议 + gw3761.ResolvingData(cmdid, rterminal, receivedata, 0, "0001", + afncode, Fn, batchtime, taskidString, this.outdata); + } + } + + // **************************************3761命令相关********************************************* + /** + * 获取设置命令 datas 具体设置的报文 terminal 集中器通信地址 + */ + private class Cmdinfor { + String afn; // AFN + String Comid; // 通信地址 + String datas; // 数据区内容 + Boolean FCV; // 帧计数有效位FCV + String FCB; // FCB + String host; // 主站地址 + String PWD; // 密码 + int PFC; // PFC + Boolean bTime; // 是否有时间标签 + Boolean TP;// 是否有时间标签 + + public void Create(String afn, String comid, String datas, int PFC, + Boolean btime) { + datas = datas.replace(" ", ""); + datas = datas.trim(); + this.afn = afn; + while (comid.length() < 8) + comid = "0" + comid; + this.Comid = comid; + this.datas = datas; + this.FCV = false; + this.PFC = PFC; + this.FCB = "01"; + this.host = "02"; + this.PWD = "00000000000000000000000000000000";// 固定密码 16个零 + this.bTime = btime; + this.TP = btime; + } + + } + + private Cmdinfor cmdinfor = new Cmdinfor(); + + /** + * 获取相应的功能码 + * + * @param sType + * @param sFCB + * @param bFCV + * @return + */ + private Integer GetDownCortrolByte(String sType, String sFCB, Boolean bFCV) { + String temp = ""; + sType = sType.toUpperCase(); + sType = sType.trim(); + if (sType.equals("00")) + temp = "0001"; + if (sType.equals("02")) + temp = "1001"; + if (sType.equals("03")) + temp = "1011"; + if (sType.equals("04")) + temp = "1010"; + if (sType.equals("05")) + temp = "1010"; + if (sType.equals("06")) + temp = "1011"; + if (sType.equals("08")) + temp = "1011"; + if (sType.equals("09")) + temp = "1011"; + if (sType.equals("0A")) + temp = "1011"; + if (sType.equals("0B")) + temp = "1011"; + if (sType.equals("0C")) + temp = "1011"; + if (sType.equals("0D")) + temp = "1011"; + if (sType.equals("0E")) + temp = "1011"; + if (sType.equals("0F")) + temp = "1011"; + if (sType.equals("10")) + temp = "1011"; + if (sType.equals("8C")) + temp = "1011"; + if (sType.equals("A4")) + temp = "1010"; + if (sType.equals("A5")) + temp = "1010"; + if (sType.equals("AA")) + temp = "1011"; + if (sType.equals("AC")) + temp = "1011"; + if (sType.equals("AD")) + temp = "1011"; + if (bFCV) + temp = "01" + sFCB.substring(1, 2) + "1" + temp; + else + temp = "01" + sFCB.substring(1, 2) + "0" + temp; + return binaryString2Int(temp); + } + + private Boolean CheckDwnPw(String sType) { + Boolean sign = false; + if (sType.equals("01")) + sign = true; + if (sType.equals("03")) + sign = true; + if (sType.equals("04")) + sign = true; + if (sType.equals("05")) + sign = true; + if (sType.equals("06")) + sign = true; + if (sType.equals("0F")) + sign = true; + if (sType.equals("10")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("A4")) + sign = true; + if (sType.equals("A5")) + sign = true; + return sign; + } + + private String GetSendCmd(Cmdinfor cmdinfor) { + int count = cmdinfor.datas.length(); + int i; + String temp; + for (i = 0; i < msg.length; i++) + msg[i] = 0; + + // 报文头 + msg[0] = 0x68;// 68H + msg[5] = 0x68;// 68H + // 控制码 + msg[6] = GetDownCortrolByte(cmdinfor.afn, cmdinfor.FCB, cmdinfor.FCV);// C + // 控制位 + // 通信地址 16进制字 + temp = cmdinfor.Comid.substring(0, 4); + msg[8] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + msg[7] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + temp = cmdinfor.Comid.substring(4); + msg[10] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 + // --> + // 行政区划码 + // A2 + // 2字节 + // BCD码 + msg[9] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A2 + // 2字节 BCD码 + // 主站地址 + msg[11] = (Integer.parseInt(cmdinfor.host, 16) << 1) & 0xFF;// A 地址域 --> + // 主站地址 A3 + // 1字节 Bin码 + msg[12] = Integer.parseInt(cmdinfor.afn, 16) & 0xFF; // AFN + if (cmdinfor.bTime) + temp = "1111"; + else + temp = "0111"; + msg[13] = (binaryString2Int(temp) << 4) + (cmdinfor.PFC % 16); // SEQ + // 帧序列域 + int len = cmdinfor.datas.length() / 2; + for (int j = 0; j < (len); j++) { + temp = cmdinfor.datas.substring(j * 2, (j * 2 + 2)); + msg[14 + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 13; + if (CheckDwnPw(cmdinfor.afn)) { + len++; + for (int j = 0; j < 16; j++) { // 密码 + temp = cmdinfor.PWD.substring(j * 2, (j * 2 + 2)); + msg[len + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 15; + } + + if (cmdinfor.TP) { + SimpleDateFormat tempDate = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + String datetime = tempDate.format(new Date()); + len++; + msg[len] = cmdinfor.PFC;// 启动帧帧序号计数器PFC + len++; + msg[len] = Integer.parseInt(datetime.substring(17, 19), 16);// 启动帧发送时标 + // 秒 + len++; + msg[len] = Integer.parseInt(datetime.substring(14, 16), 16);// 启动帧发送时标 + // 分 + len++; + msg[len] = Integer.parseInt(datetime.substring(11, 13), 16);// 启动帧发送时标 + // 时 + len++; + msg[len] = Integer.parseInt(datetime.substring(8, 10), 16);// 启动帧发送时标 + // 日 + len++; + msg[len] = 1;// 允许发送传输延时时间 + } + len++; + msg[len] = GetCS(len); + len++; + msg[len] = 0x16; + count = len - 7; + count = (count << 2) + 2; + msg[1] = count % 0x100; + msg[2] = count / 0x100; + msg[3] = count % 0x100; + msg[4] = count / 0x100; + + // 转成字符串 + StringBuffer sendBuffer = new StringBuffer(); + for (int j = 0; j <= len; j++) + sendBuffer.append(" " + dec2Hex(msg[j], 2)); + + return sendBuffer.toString().trim(); + } + + private int GetCS(int len) { + int ics = 0; + for (int i = 6; i < len; i++) { + ics = ics + msg[i]; + } + return ics & 0xFF; + } + + private int GetPFC() { + return 1; + } + + /** + * 二进制字符串转整型 + * + * @param bString + * @return + */ + public int binaryString2Int(String bString) { + int temp = 0; + for (int i = 0; i < bString.length(); i++) { + temp <<= 1; + temp += Integer.parseInt(bString.substring(i, i + 1)); + } + return temp; + } + + /** + * 10进制转16进制 + * + * @param dec + * 要转换的数值 + * @param len + * 16进制的长度 + * @return + */ + public String dec2Hex(int dec, int len) { + String tempString = Integer.toHexString(dec); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + +} diff --git a/selfDevelop/src/main/java/com/back/communication/SerialSMS.java b/selfDevelop/src/main/java/com/back/communication/SerialSMS.java new file mode 100644 index 0000000..f96a0e5 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SerialSMS.java @@ -0,0 +1,335 @@ +package com.back.communication; + +import com.back.common.Common; +import gnu.io.CommPortIdentifier; +import gnu.io.NoSuchPortException; +import gnu.io.PortInUseException; +import gnu.io.SerialPort; +import gnu.io.SerialPortEvent; +import gnu.io.SerialPortEventListener; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; + +import com.back.action.Log; + +public class SerialSMS implements SerialPortEventListener { + + public final static String PORT_OWER = "SMS"; + + private boolean isOpen; + + private boolean isStart; + + private String portName; + private String commSet; + + private CommPortIdentifier portId; + + private SerialPort serialPort; + + private DataInputStream inputStream; + + private OutputStream outputStream; + + private Object readWriteLock = new Object(); + + private String serialdata = ""; + + Boolean isread = false; + + private String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public static SerialSMS Instance; + + public static SerialSMS getInstance(String port, String smsset) { + if (Instance == null) { + Instance = new SerialSMS(port, smsset); + } + + return Instance; + } + + private SerialSMS(String port, String smsset) { + isOpen = false; + isStart = false; + + portName = port; + commSet = smsset; + } + + public void init() throws IOException, Exception { + if (isOpen) { + close(); + } + + try { + // 根据传入的串口名创建串口标识 + portId = CommPortIdentifier.getPortIdentifier(portName); + // 打开串口并返回串口对象 + serialPort = (SerialPort) portId.open(PORT_OWER, 2000); + + // 通过串口对象获得输入流 + inputStream = new DataInputStream(serialPort.getInputStream()); + + // 通过串口对象获得输出流 + outputStream = serialPort.getOutputStream(); + + serialPort.getReceiveTimeout(); + + isOpen = true; + } catch (NoSuchPortException ex) { + ex.printStackTrace(); + System.err.println(ex.getMessage()); + } catch (PortInUseException ex) { + System.err.println(ex.getMessage()); + } + } + + public void start() throws Exception { + if (!isOpen) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->" + + portName + " has not been opened."); + } + + // 设置串口监听对象 + serialPort.addEventListener(this); + + // 设置串口数据可用 + serialPort.notifyOnDataAvailable(true); + + /* 设置串口初始化参数,依次是波特率,校验位,数据位,停止位 */ + String[] array = commSet.split(","); + int baud = Integer.parseInt(array[0]); + int databits = Integer.parseInt(array[2]); + int stopbits = Integer.parseInt(array[3]); + String parity = array[1].toLowerCase(); + int intparity = 0; + if (parity.equals("n")) { + intparity = 0; + } else if (parity.equals("o")) { + intparity = 1; + } else if (parity.equals("e")) { + intparity = 2; + } + serialPort.setSerialPortParams(baud, databits, stopbits, intparity); + + isStart = true; + } + + public void stop() { + if (isStart) { + // 设置串口数据是否可用 + serialPort.notifyOnDataAvailable(false); + + // 移除串口监听事件 + serialPort.removeEventListener(); + + isStart = false; + } + } + + public void close() { + stop(); + + if (isOpen) { + try { + // 关闭流对象与串口对象 + inputStream.close(); + outputStream.close(); + serialPort.close(); + serialPort = null; + + isOpen = false; + } catch (IOException ex) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Error:" + ex.getMessage()); + + } + } + } + + public void serialEvent(SerialPortEvent event) { + switch (event.getEventType()) { + case SerialPortEvent.BI: + case SerialPortEvent.OE: + case SerialPortEvent.FE: + case SerialPortEvent.PE: + case SerialPortEvent.CD: + case SerialPortEvent.CTS: + case SerialPortEvent.DSR: + case SerialPortEvent.RI: + case SerialPortEvent.OUTPUT_BUFFER_EMPTY: + break; + case SerialPortEvent.DATA_AVAILABLE: + // 从串口获得数据,获取的数据以流的形式读取 + readComm(); + break; + default: + break; + } + } + + public boolean writeCommTxt(String phone, String Msg) { + synchronized (readWriteLock) { + boolean flag = false; + + try { + String data = "AT+CMGF=1\r\n";// 文本发送 + serialdata = ""; + outputStream.write(data.getBytes()); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->write AT+CMGF=1 .......1"); + for (int i = 0; i < 5000; i++) // 2012-06-20 + { + if (serialdata.contains("-4F-4B-")) { // OK + break; + } + + Thread.sleep(1); + } + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->write AT+CMGF=1 .......2"); + if (serialdata.contains("-4F-4B-")) { + serialdata = ""; + flag = true; + } else { + return false; + } + + data = "AT+CSCS=\"GSM\"\r\n"; + serialdata = ""; + outputStream.write(data.getBytes()); + + for (int i = 0; i < 500; i++) { + if (serialdata.contains("-4F-4B-")) { + break; + } + Thread.sleep(1); + } + serialdata = ""; + + // data = center + code; + serialdata = ""; + Msg = ">" + Msg; + outputStream.write(Msg.getBytes()); + outputStream.write((char) 26);// ctrl+Z发送 + for (int i = 0; i < 10000; i++) // 2012-06-20 + { + + if (serialdata.contains("-4F-4B-")) { + break; + } + + Thread.sleep(1); + } + + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.toString()); + e.printStackTrace(); + } + if (serialdata.contains("-4F-4B-")) { // 发送成功 + flag = true; + } else { + flag = false; + } + return flag; + } + } + + /** 写指令到串口 */ + public boolean writeComm(String center, String code) { + synchronized (readWriteLock) { + boolean flag = false; + + try { + String data = "AT+CMGF=0\r\n";// 文本发送 设置为PDU模式 + serialdata = ""; + outputStream.write(data.getBytes()); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->write AT+CMGF=0 .......1"); + for (int i = 0; i < 5000; i++) // 2012-06-20 + { + if (serialdata.contains("-4F-4B-")) { // OK + break; + } + + Thread.sleep(1); + } + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->write AT+CMGF=0 .......2"); + if (serialdata.contains("-4F-4B-")) { + serialdata = ""; + flag = true; + } else { + return false; + } + + if (flag) { + int intLen = code.length() / 2; + data = "AT+CMGS=" + intLen + "\r\n"; + serialdata = ""; + outputStream.write(data.getBytes()); + + for (int i = 0; i < 500; i++) { + if (serialdata.contains("-4F-4B-")) { + break; + } + Thread.sleep(1); + } + serialdata = ""; + + // data = center + code; + data = code; + serialdata = ""; + outputStream.write(data.getBytes()); + outputStream.write((char) 26);// ctrl+Z发送 + for (int i = 0; i < 10000; i++) // 2012-06-20 + { + + if (serialdata.contains("-4F-4B-")) { + break; + } + + Thread.sleep(1); + } + } + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.toString()); + e.printStackTrace(); + } + if (serialdata.contains("-4F-4B-")) { // 发送成功 + flag = true; + } else { + flag = false; + } + return flag; + } + } + + /** 用流读取数据,写事件表和写结果表 */ + public void readComm() { + int num = 0;// buffer中的数据长度 + byte[] readbuffer = new byte[1024]; + try { + if (inputStream.available() > 0) { + num = inputStream.read(readbuffer); + } else { + return; + } + serialdata = serialdata + Common.GetHexStr(readbuffer, num); + } catch (IOException e) { + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.toString()); + return; + } + } +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/communication/SocketComm.java b/selfDevelop/src/main/java/com/back/communication/SocketComm.java new file mode 100644 index 0000000..4f9f332 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SocketComm.java @@ -0,0 +1,251 @@ +package com.back.communication; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import com.back.action.Log; +import com.back.common.Common; +import com.back.protocol.GW3761; +import com.back.protocol.Lon16; + +public class SocketComm { + + Lon16 lon16 = new Lon16(); + GW3761 gw3761 = new GW3761(); + private String language = ""; + private String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public SocketComm(String language) { + this.language = language; + lon16.Setlanguage(language); + gw3761.Setlanguage(language); + } + + /** + * 发送Socket报文 + * + * @param threadid + * 线程ID + * @param ruletype + * 规约类型 + * @param terminal + * 集中器地址 + * @param command + * 转发时的命令 + * @param cmdid + * 转发时的命令ID + * @param ipadd + * GPRS服务器地址 + * @param port + * GPRS服务器端口 + * @param resend + * 重发次数 + * @param timeout + * 超时时间 + * @param afncode + * @param pn + * @param batchtime + * 定采开始时间 + * @param responsetype + * 接收标志 1 不接收 2接收并作光控应答处理 + * @param taskidString + * 定采的数据时标 + */ + public void Send(String threadid, String ruletype, String terminal, String command, int cmdid, String ipadd, + int port, int resend, int timeout, String afncode, int pn, String batchtime, String responsetype, + String taskidString) { + int count = 0; + int state = 0; + + String cmdreturn = ""; + Socket socket = null; + // 获得对应socket的输入/输出流 + InputStream is = null; + OutputStream os = null; + // 建立数据流 + DataInputStream dis = null; + DataOutputStream dos = null; + String describe = ""; + // if (cmdid == 0) { + // + // describe = "[Auto tasks]";// 后台抄表任务 + // } + try { + socket = new Socket(ipadd, port); + } catch (Exception e) {// socket连接失败 + + state = 4;// GPRS服务器连接失败 + if (!describe.equals("")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + ":" + threadid + ":" + String.valueOf(cmdid) + "] Send:" + e.getMessage() + " " + describe); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + threadid + + ":" + String.valueOf(cmdid) + "] ERROR:" + e.getMessage()); + + // 需要提示到界面,事务与前置机通信有问题. ?????????????????????? + + // 将定采数据或曲线命令保存在补抄表中 + if (!ruletype.equals("0001")) { + if (afncode == null || afncode.equals("")) + gw3761.ResolvingData(cmdid, terminal, cmdreturn, state, "0002", afncode, pn, batchtime, + taskidString, command); + } + // 2015 07 16 wwb 补抄数据 + // gw3761.complementary_data(terminal,command,batchtime); + return; + } + + if (cmdid == 0) { + // 2017 10 15 定采任务 只抄一次 + resend = 1; + describe = "[Auto tasks]";// 后台抄表任务 + } + + boolean luxAck = false;// 光控命令 应答成功 + if (state == 0) { + while (count < resend) {// 处理错误(超时)重发 + try { + socket.setSoTimeout(60000);// 设置超时时间 + // 获得对应socket的输入/输出流 + is = socket.getInputStream(); + os = socket.getOutputStream(); + // 建立数据流 + dis = new DataInputStream(is); + dos = new DataOutputStream(os); + if (!describe.equals("")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]=>GPRS: " + describe); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]cammondid" + cmdid + "=>GPRS:" + command); + + byte[] getbytes; + int len; + + if (ruletype.equals("0001"))// Lon16 + { // LON16是ASC码 可以直接发送 + // byte[] str = lon16.GetSendCmd(terminal,command); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->lon16 Send Cmd :" + command); + dos.write(lon16.GetSendCmd(terminal, command));// 转发到服务器 + } else { + command = command.replace("-", ""); + + if (!command.substring(0, 2).equals("68")) {// 服务器内部命令 + // dos.write(command.getBytes());// + // 转发到服务器 + dos.write(lon16.GetSendCmd("0000" + terminal, command));// 转发到服务器 + } else { // 正常的国网命令 + len = command.length() / 2 + command.length() % 2; + getbytes = new byte[len]; + for (int i = 0; i < len; i++) { + String temp = command.substring(i * 2, i * 2 + 2); + getbytes[i] = (byte) Integer.parseInt(temp, 16); + } + dos.write(getbytes);// 转发到服务器 + } + } + + if (!responsetype.equals("1")) {// 增加需应答时处理2011-06-28 + // 从服务器获取数据 + int num = 0;// buffer中的数据长度 + byte[] readbuffer = new byte[1024]; + num = dis.read(readbuffer); + // 报文头是68--3761协议指令 + if (readbuffer[0] == 0x68) { + cmdreturn = Common.GetHexStr(readbuffer, num); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]<= GPRS: cmdreturn->" + cmdreturn); + cmdreturn = cmdreturn.substring(0, cmdreturn.length() - 1); + + if (readbuffer.length > 20)// 应答确认帧 + { + if ((readbuffer[12] == 0x00) && (readbuffer[14] == 0x00) && (readbuffer[15] == 0x00) + && (readbuffer[16] == 0x01) && (readbuffer[17] == 0x00)) { + luxAck = true; + } + } + + } else {// 其它状态 + cmdreturn = Common.GetHexStr(readbuffer, num); + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]<= GPRS: cmdreturn->" + cmdreturn); + // 转成ASC码 + cmdreturn = cmdreturn.replace("-", "").replace("0D0A", ""); + cmdreturn = Common.HexStr2AsciiStr(cmdreturn); + cmdreturn = cmdreturn.substring(13); + + } + if (cmdreturn.equals("")) {// 接收数据超时 + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]<= GPRS: time out!" + describe); + } else {// 接收到指令 + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]<=GPRS:" + cmdreturn); + } + } + break; + } catch (Exception e) {// 接收超时 + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]<= read Error! " + e.getMessage()); + state = 3; + count += 1; + } + } + try { + dis.close(); // 关闭数据输入流 + dos.close(); // 关闭数据输出流 + is.close(); // 关闭输入流 + os.close(); // 关闭输出流 + socket.close(); // 关闭socket + dis = null; + dos = null; + is = null; + os = null; + socket = null; + } catch (IOException e) { + e.printStackTrace(); + } + } + + // 光控处理 20180421 + // if (luxAck==true && cmdid == 0) + // { + // com.back.protocol.Protocol.updateTerminalsLuxState(terminal); + // cmdreturn = ""; + // return; + // } + + // 写入结果表 + if (cmdreturn.endsWith("No Connected")) { + state = 1; + if (!command.equals("PEAK")) + cmdreturn = ""; + } else if (cmdreturn.endsWith("Busy")) { + state = 2; + cmdreturn = ""; + // batchtime taskidString + // if (!taskidString.equals(""))//再重新定采数据 + // com.back.protocol.Protocol.upatetempmeters(batchtime, + // taskidString); + } + + if (cmdreturn.equals("")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]<= GPRS: time out!" + describe); + + if (ruletype.equals("0001")) {// 龙电协议Lon16 + lon16.ResolvingData(cmdid, command, terminal, cmdreturn, state, "0002", batchtime, taskidString); + } else {// 国网3761协议 + gw3761.ResolvingData(cmdid, terminal, cmdreturn, state, "0002", afncode, pn, batchtime, taskidString, + command); + } + } +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/communication/SocketComm485.java b/selfDevelop/src/main/java/com/back/communication/SocketComm485.java new file mode 100644 index 0000000..1d9ef81 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/SocketComm485.java @@ -0,0 +1,922 @@ +package com.back.communication; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.sql.ResultSet; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.jdbc.SQLHelper; +import com.back.protocol.GW3761; +import com.back.protocol.Lon16; + +/** + * 485总线集中器处理流程处理 + * 适用于 RJ45转485 的转换器 + * @author Administrator + * + */ +public class SocketComm485 { + + public static int beat485;// 485集中器跳时间 (毫秒) + public static int comTimeOut485;// 集中器连接串口(毫秒) + public final static String PORT_OWER = "App"; + + private LinkedList cmdQueue = new LinkedList(); // 命令处理队列 + private List termina485lList = new ArrayList(); // 485集中器队列 + String receivedata = "";// 串口接收数据 + private int msg[] = new int[2024]; + + private int readMsg[] = new int[2024]; // 接收缓存 + private int readMsgCount = 0; // 接收到的字节数 + + String ipadd = "192.168.1.40"; + int port = 2323; + + Boolean isread = false; + private boolean pCmd = false; + + Lon16 lon16 = new Lon16(); + GW3761 gw3761 = new GW3761(); + private String clazzName = new Object() { + public String getClassName() + { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + + /** + * 485总线任务 + * + * @throws InterruptedException + */ + public void RS485Bus_Task() throws InterruptedException { + // 获取485集中器 + String strsql = "SELECT comid FROM terminals WHERE terminals.ComModel='0003'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + termina485lList.clear(); + // 获取485集中器通信地址 + try { + while (rSet.next()) { + termina485lList.add(rSet.getString("comid")); + } + + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Load terminal 485 ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Close ERROR:" + e.getMessage()); + } + String comidString = ""; + int count = 0; + int tCount = termina485lList.size(); + // 事件轮巡时间 3S + int iMax = beat485 / 100 / tCount; + if (iMax < 1) + iMax = 1; + + + //建 立 TCP 连接 + try { + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + ipadd = "192.168.1.40"; + port = 2323; + + // 485集中器轮巡处理 + while (termina485lList.size() > 0) { + + if (cmdQueue.size() > 0) // 页面任务 + { // 转发命令处理 + CmdObject485 cmdObject485 = cmdQueue.get(0); + cmdQueue.remove(0); + + //获取集中器所在 中断器的 IP地址 + ipadd = getConvertIP(cmdObject485.terminal).trim(); + if (ipadd.equals("")) + { //中断转换器的 IP地址无 + continue; + } + + pCmd = true; + Send(cmdObject485.ruletype,cmdObject485.terminal, + cmdObject485.outdata, cmdObject485.cmdid, ipadd,port,1,comTimeOut485,"",0,"", + cmdObject485.responsetype, ""); + // 清除相应集中器 + int i = termina485lList.indexOf(cmdObject485.cmdid); + if (i > -1) + termina485lList.remove(i); + + continue; + } + count++; + Thread.sleep(100); + // 如果此处理轮巡周期长的话, + + if (count < iMax) { + continue; + } + pCmd = false; + count = 0; + comidString = termina485lList.get(0); + termina485lList.remove(0); + + ipadd = getConvertIP(comidString).trim(); + if (ipadd.equals("")) + { //中断转换器的 IP地址无 + continue; + } + // 轮巡任务处理**************************************** + try { + BeatTask(comidString); + } catch (Exception e) { + Log.writelog(clazzName, Thread.currentThread() + .getStackTrace()[1].getMethodName() + + "->[" + + comidString + "]BeatTask Error:" + e.getMessage()); + } + + }// termina485lList.size() > 0 + } + + /** + * + * @param comidString + * @return + */ + private String getConvertIP(String comidString) { + String sql = "select convertIP from terminals where comid='" + + comidString + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(sql); + if (rSet == null) { + return ""; + } + String strIp = ""; + try { + while (rSet.next()) { + strIp = rSet.getString("convertIP"); + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog( + clazzName, + Thread.currentThread().getStackTrace()[1] + .getMethodName() + "->ERROR:" + e.getMessage()); + } + + return strIp; + } + /** + * 更新485集中器状态 + * + * @param comidString + * @param onLineSate + */ + private void UpdateTerminalOnLineState(String comidString, + boolean onLineSate) { + String sql = ""; + if (onLineSate) + sql = "update terminals set onlinestate=1,onlinetime='" + + Common.getDateStr0() + "'" + "where comid='" + + comidString + "'"; + else + sql = "update terminals set onlinestate=0,onlinetime='" + + Common.getDateStr0() + "'" + "where comid='" + + comidString + "'"; + SQLHelper.ExecSql(sql); + } + + /** + * 校时处理 + */ + private boolean CheckTime(String comidString) { + // 获取报文中时间 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + String tempString = "20" + Integer.toHexString(readMsg[23]) + "-" + + Integer.toHexString(readMsg[22] & 0x3F) + "-" + + Integer.toHexString(readMsg[21]) + " " + + Integer.toHexString(readMsg[20]) + ":" + + Integer.toHexString(readMsg[19]) + ":" + + Integer.toHexString(readMsg[18]); + try { + Date date = sdf.parse(tempString); + // 计算时差 + long diff = (new Date()).getTime() - date.getTime(); + long minute = diff / (60 * 1000); + if (minute > 5) { + SendCMDCheckTime(comidString); + } + } catch (ParseException e) { + // TODO Auto-generated catch block + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Time Msg Error:" + + this.receivedata); + return false; + } + return true; + } + + /** + * 发送校时命令 A5 F31 对时命令 + * + * @param comidString + */ + private void SendCMDCheckTime(String comidString) { + Date date = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yy MM dd HH mm ss"); + String[] time = format.format(date).split(" "); + + String strMsgString = "00 00 40 03 " + time[5] + " " + time[4] + " " + + time[3] + " " + time[2] + " " + time[1] + " " + time[0]; + SendCmd(comidString, "A5", strMsgString); + if (!isread) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Check Clock Out Time!"); + return; + } + } + + /** + * 读取事件 + * + * @param comidString + */ + private void ReadEvent(String comidString) { + int control = readMsg[6]; + // 无事件标识 + if ((control & 0x20) == 0) + return; + // 确信EC的位置 + int seq = readMsg[13]; + int ec = 0; + int dbec = 0; + if ((seq & 0x80) > 0) { + ec = readMsg[readMsgCount - 10]; + } else { + ec = readMsg[readMsgCount - 4]; + } + + // 加载数据库 重要事件 计数器 + String strsql = "select ec from terminals where comid='" + comidString + + "'"; + + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + try { + while (rSet.next()) { + ec = rSet.getInt("ec"); + } + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Get Ec from DataBase ERROR:" + e.getMessage()); + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Close ERROR:" + e.getMessage()); + } + + if (dbec!=ec) + return; + int y =0; + + y= ec- dbec; + if (ec20) + ec = (dbec + 20) & 0xFF; + //读事件 只读一条 + String strMsgString = "00 00 01 00 " + Common.dec2Hex(dbec,2) + " " + Common.dec2Hex(ec,2); + + pCmd = true; + SendCmd(comidString, "0E", strMsgString); + + + //更新数据库中记数器 + strsql = "update temrinals set ec=" + String.valueOf(ec) + " where comid='" + comidString + + "'"; + SQLHelper.ExecSql(strsql); + + } + + /* + * 命令是否合法 + */ + private boolean CheckMsg(String comidString) { + if (readMsgCount < 20) // 长度不足 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Length Error:" + + this.receivedata); + return false; + } + if (readMsg[0] != 0x68) // 第一个字节不是68 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]First Byte Not 68 Error:" + + this.receivedata); + return false; + } + if (readMsg[1] != readMsg[3] || readMsg[2] != readMsg[4]) // 两个长度不对 + { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Length Byte Error:" + + this.receivedata); + return false; + } + + // 报文长度 + int temp = (readMsg[1] + (readMsg[2] << 8)) >> 2 + 8; + if (temp != readMsgCount) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Msg Length Error:" + + this.receivedata); + return false; + } + + // 计算校验和 + int iCS = 0; + for (int i = 6; i < readMsgCount; i++) { + iCS = iCS + readMsg[i]; + } + iCS = iCS & 0xFF; + + if (iCS != readMsg[readMsgCount - 2]) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]CS Error:" + + this.receivedata); + return false; + } + + // 通信地址 不对应 + String comid = Integer.toHexString(readMsg[8]) + + Integer.toHexString(readMsg[7]) + + Integer.toHexString(readMsg[10]) + + Integer.toHexString(readMsg[9]); + if (comid.equals(comidString) == false) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + + "->[" + comidString + "]Comid Error:" + + this.receivedata); + return false; + } + return true; + } + + private void BeatTask(String comidString) { + // 下发读取时钟命令 AC 00 00 01 00 + SendCmd(comidString, "AC", "00 00 01 00"); + UpdateTerminalOnLineState(comidString, isread); + if (!isread) {// 不在线 + // 更新集中器在线状态 + return; + } + if (this.receivedata.trim().equals("")) + return; + + try { + if (CheckMsg(comidString) == false)// 没有通过数据校验 + { + return; + } + // 校时处理 + CheckTime(comidString); + // 事件读取 + ReadEvent(comidString); + } catch (Exception e) { + // TODO: handle exception + } + + } + + /** + * 下发集中器命令 + * + * @param terminalComid + * @param Afn + * @param + */ + private void SendCmd(String terminalComid, String Afn, String Data) { + cmdinfor.Create(Afn, terminalComid, Data, GetPFC(), false); + String outdata = GetSendCmd(cmdinfor); + Send("0002",terminalComid, + outdata, 0, ipadd,port,1,comTimeOut485,"",0,"", + "1", ""); + } + + /** + * 发送Socket报文 + * @param ruletype 线程ID + * @param ruletype 规约类型 + * @param terminal 集中器地址 + * @param command 转发时的命令 + * @param cmdid 转发时的命令ID + * @param ipadd GPRS服务器地址 + * @param port GPRS服务器端口 + * @param resend 重发次数 + * @param timeout 超时时间 + * @param afncode + * @param pn + * @param batchtime 定采开始时间 + * @param responsetype 接收标志 1 不接收 + * @param taskidString 定采的数据时标 + */ + public void Send(String ruletype, String terminal, String command, int cmdid, String ipadd, int port, int resend, int timeout, String afncode, int pn, String batchtime, + String responsetype, String taskidString) { + + int count = 0; + int state = 0; + + String cmdreturn = ""; + Socket socket = null; + // 获得对应socket的输入/输出流 + InputStream is = null; + OutputStream os = null; + // 建立数据流 + DataInputStream dis = null; + DataOutputStream dos = null; + String describe=""; + if (cmdid==0) + { + describe = "[Auto Tasks]";//后抄表任务 + } + try { + socket = new Socket(ipadd, port); + } catch (Exception e) {// socket连接失败 + + state = 4;// GPRS服务器连接失败 + if (!describe.equals("")) + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal +":"+ String.valueOf(cmdid)+ "] Send:" + e.getMessage() + " " + describe); + else + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + ":"+ String.valueOf(cmdid)+ "] ERROR:" + e.getMessage()); + + + //将定采数据或曲线命令保存在补抄表中 + if (!ruletype.equals("0001")) { + if (afncode ==null || afncode.equals("") ) + gw3761.ResolvingData(cmdid, terminal, cmdreturn, state, "0002", afncode, pn, batchtime, taskidString,command); + } + + return; + } + + if (state == 0) { + while (count < resend) {// 处理错误(超时)重发 + try { + socket.setSoTimeout(timeout);// 设置超时时间 + // 获得对应socket的输入/输出流 + is = socket.getInputStream(); + os = socket.getOutputStream(); + // 建立数据流 + dis = new DataInputStream(is); + dos = new DataOutputStream(os); + if (!describe.equals("")) + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal + "]=>GPRS: " + describe); + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal + "]=>GPRS:" + command); + + + byte[] getbytes; + int len; + + if (ruletype.equals("0001"))//Lon16 + { //LON16是ASC码 可以直接发送 + //byte[] str = lon16.GetSendCmd(terminal,command); + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->lon16 Send Cmd :" + command); + dos.write(lon16.GetSendCmd(terminal,command));// 转发到服务器 + }else + { + command = command.replace("-", ""); + + if (!command.substring(0, 2).equals("68")) + {//服务器内部命令 + //dos.write(command.getBytes());// 转发到服务器 + dos.write(lon16.GetSendCmd("0000" + terminal,command));// 转发到服务器 + } + else + { //正常的国网命令 + len = command.length() / 2 + command.length() % 2; + getbytes = new byte[len]; + for (int i = 0; i < len; i++) { + String temp = command.substring(i * 2, i * 2 + 2); + getbytes[i] = (byte) Integer.parseInt(temp, 16); + } + dos.write(getbytes);// 转发到服务器 + } + } + + + + if (!responsetype.equals("1")) {// 增加需应答时处理2011-06-28 + // 从服务器获取数据 + int num = 0;// buffer中的数据长度 + byte[] readbuffer = new byte[1024]; + num = dis.read(readbuffer); + //报文头是68 + if (readbuffer[0] ==0x68 ) { + cmdreturn = Common.GetHexStr(readbuffer, num); + cmdreturn = cmdreturn.substring(0, cmdreturn.length() - 1); + + System.arraycopy(readbuffer, 0, readMsg, 0, num); + readMsgCount = num; + } else { + cmdreturn = Common.GetHexStr(readbuffer, num); + //转成ASC码 + cmdreturn = cmdreturn.replace("-", "").replace("0D0A", ""); + cmdreturn = Common.HexStr2AsciiStr(cmdreturn); + cmdreturn = cmdreturn.substring(13);//去掉通信地址 + + } + if (cmdreturn.equals("")) + { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal + "]<= GPRS: time out!" + describe); + } + else { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal + "]<=GPRS:" + cmdreturn); + } + } + break; + } catch (Exception e) {// 接收超时 + state = 3; + count += 1; + } + } + try { + dis.close(); // 关闭数据输入流 + dos.close(); // 关闭数据输出流 + is.close(); // 关闭输入流 + os.close(); // 关闭输出流 + socket.close(); // 关闭socket + dis = null; + dos = null; + is = null; + os = null; + socket = null; + } catch (IOException e) { + e.printStackTrace(); + } + } + + // 写入结果表 + if (cmdreturn.endsWith("No Connected")) { + state = 1; + if (!command.equals("PEAK")) + cmdreturn=""; + } else if (cmdreturn.endsWith("Busy")) { + state = 2; + cmdreturn=""; + } + + if (cmdreturn.equals("")) + { + Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal + "]<= GPRS: time out!" + describe); + isread = false; + } + else + isread = true; + + // + if (pCmd == false) + return; + + //解码处理 + if (ruletype.equals("0001")) { + lon16.ResolvingData(cmdid,command, terminal, cmdreturn, state, "0002", batchtime,taskidString); + } else { + gw3761.ResolvingData(cmdid, terminal, cmdreturn, state, "0002", afncode, pn, batchtime, taskidString,command); + } + } + // **************************************3761命令相关********************************************* + /** + * 获取设置命令 datas 具体设置的报文 terminal 集中器通信地址 + */ + private class Cmdinfor { + String afn; // AFN + String Comid; // 通信地址 + String datas; // 数据区内容 + Boolean FCV; // 帧计数有效位FCV + String FCB; // FCB + String host; // 主站地址 + String PWD; // 密码 + int PFC; // PFC + Boolean bTime; // 是否有时间标签 + Boolean TP;// 是否有时间标签 + + public void Create(String afn, String comid, String datas, int PFC, + Boolean btime) { + datas = datas.replace(" ", ""); + datas = datas.trim(); + this.afn = afn; + while (comid.length() < 8) + comid = "0" + comid; + this.Comid = comid; + this.datas = datas; + this.FCV = false; + this.PFC = PFC; + this.FCB = "01"; + this.host = "02"; + this.PWD = "00000000000000000000000000000000";// 固定密码 16个零 + this.bTime = btime; + this.TP = btime; + } + + } + + private Cmdinfor cmdinfor = new Cmdinfor(); + + /** + * 获取相应的功能码 + * + * @param sType + * @param sFCB + * @param bFCV + * @return + */ + private Integer GetDownCortrolByte(String sType, String sFCB, Boolean bFCV) { + String temp = ""; + sType = sType.toUpperCase(); + sType = sType.trim(); + if (sType.equals("00")) + temp = "0001"; + if (sType.equals("02")) + temp = "1001"; + if (sType.equals("03")) + temp = "1011"; + if (sType.equals("04")) + temp = "1010"; + if (sType.equals("05")) + temp = "1010"; + if (sType.equals("06")) + temp = "1011"; + if (sType.equals("08")) + temp = "1011"; + if (sType.equals("09")) + temp = "1011"; + if (sType.equals("0A")) + temp = "1011"; + if (sType.equals("0B")) + temp = "1011"; + if (sType.equals("0C")) + temp = "1011"; + if (sType.equals("0D")) + temp = "1011"; + if (sType.equals("0E")) + temp = "1011"; + if (sType.equals("0F")) + temp = "1011"; + if (sType.equals("10")) + temp = "1011"; + if (sType.equals("8C")) + temp = "1011"; + if (sType.equals("A4")) + temp = "1010"; + if (sType.equals("A5")) + temp = "1010"; + if (sType.equals("AA")) + temp = "1011"; + if (sType.equals("AC")) + temp = "1011"; + if (sType.equals("AD")) + temp = "1011"; + if (bFCV) + temp = "01" + sFCB.substring(1, 2) + "1" + temp; + else + temp = "01" + sFCB.substring(1, 2) + "0" + temp; + return binaryString2Int(temp); + } + + private Boolean CheckDwnPw(String sType) { + Boolean sign = false; + if (sType.equals("01")) + sign = true; + if (sType.equals("03")) + sign = true; + if (sType.equals("04")) + sign = true; + if (sType.equals("05")) + sign = true; + if (sType.equals("06")) + sign = true; + if (sType.equals("0F")) + sign = true; + if (sType.equals("10")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("A4")) + sign = true; + if (sType.equals("A5")) + sign = true; + return sign; + } + + private String GetSendCmd(Cmdinfor cmdinfor) { + int count = cmdinfor.datas.length(); + int i; + String temp; + for (i = 0; i < msg.length; i++) + msg[i] = 0; + + // 报文头 + msg[0] = 0x68;// 68H + msg[5] = 0x68;// 68H + // 控制码 + msg[6] = GetDownCortrolByte(cmdinfor.afn, cmdinfor.FCB, cmdinfor.FCV);// C + // 控制位 + // 通信地址 16进制字 + temp = cmdinfor.Comid.substring(0, 4); + msg[8] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + msg[7] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + temp = cmdinfor.Comid.substring(4); + msg[10] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 + // --> + // 行政区划码 + // A2 + // 2字节 + // BCD码 + msg[9] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A2 + // 2字节 BCD码 + // 主站地址 + msg[11] = (Integer.parseInt(cmdinfor.host, 16) << 1) & 0xFF;// A 地址域 --> + // 主站地址 A3 + // 1字节 Bin码 + msg[12] = Integer.parseInt(cmdinfor.afn, 16) & 0xFF; // AFN + if (cmdinfor.bTime) + temp = "1111"; + else + temp = "0111"; + msg[13] = (binaryString2Int(temp) << 4) + (cmdinfor.PFC % 16); // SEQ + // 帧序列域 + int len = cmdinfor.datas.length() / 2; + for (int j = 0; j < (len); j++) { + temp = cmdinfor.datas.substring(j * 2, (j * 2 + 2)); + msg[14 + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 13; + if (CheckDwnPw(cmdinfor.afn)) { + len++; + for (int j = 0; j < 16; j++) { // 密码 + temp = cmdinfor.PWD.substring(j * 2, (j * 2 + 2)); + msg[len + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 15; + } + + if (cmdinfor.TP) { + SimpleDateFormat tempDate = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + String datetime = tempDate.format(new Date()); + len++; + msg[len] = cmdinfor.PFC;// 启动帧帧序号计数器PFC + len++; + msg[len] = Integer.parseInt(datetime.substring(17, 19), 16);// 启动帧发送时标 + // 秒 + len++; + msg[len] = Integer.parseInt(datetime.substring(14, 16), 16);// 启动帧发送时标 + // 分 + len++; + msg[len] = Integer.parseInt(datetime.substring(11, 13), 16);// 启动帧发送时标 + // 时 + len++; + msg[len] = Integer.parseInt(datetime.substring(8, 10), 16);// 启动帧发送时标 + // 日 + len++; + msg[len] = 1;// 允许发送传输延时时间 + } + len++; + msg[len] = GetCS(len); + len++; + msg[len] = 0x16; + count = len - 7; + count = (count << 2) + 2; + msg[1] = count % 0x100; + msg[2] = count / 0x100; + msg[3] = count % 0x100; + msg[4] = count / 0x100; + + // 转成字符串 + StringBuffer sendBuffer = new StringBuffer(); + for (int j = 0; j <= len; j++) + sendBuffer.append(" " + dec2Hex(msg[j], 2)); + + return sendBuffer.toString().trim(); + } + + private int GetCS(int len) { + int ics = 0; + for (int i = 6; i < len; i++) { + ics = ics + msg[i]; + } + return ics & 0xFF; + } + + private int GetPFC() { + return 1; + } + + /** + * 二进制字符串转整型 + * + * @param bString + * @return + */ + public int binaryString2Int(String bString) { + int temp = 0; + for (int i = 0; i < bString.length(); i++) { + temp <<= 1; + temp += Integer.parseInt(bString.substring(i, i + 1)); + } + return temp; + } + + /** + * 10进制转16进制 + * + * @param dec + * 要转换的数值 + * @param len + * 16进制的长度 + * @return + */ + public String dec2Hex(int dec, int len) { + String tempString = Integer.toHexString(dec); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/communication/Wechat.java b/selfDevelop/src/main/java/com/back/communication/Wechat.java new file mode 100644 index 0000000..5bced11 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/Wechat.java @@ -0,0 +1,253 @@ +package com.back.communication; + +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.CookieStore; +import org.apache.http.client.HttpClient; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.config.AuthSchemes; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.cookie.Cookie; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.*; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + + + +//发送微信报警 + +public class Wechat { + public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/gettoken";// 获取access + public static String ACCESS_TOKEN = ""; // url + public static final String CorpID = "wx8940fac25406a4e0"; + public static final String SECRET = "-My5wZv8N1hw7npL0vUpAvTXHp-gk8AJEO79NDba0o9dHS2fCoqHlU1jmnkFRlSM"; + public static Date outTime = new Date(); //超时间 + private static HttpClientContext context = HttpClientContext.create(); + private static SSLConnectionSocketFactory socketFactory; + private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000) + .setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT). + setExpectContinueEnabled(true). + setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)). + setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); + private static TrustManager manager = new X509TrustManager() { + + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + + private static void enableSSL() { + try { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, new TrustManager[]{manager}, null); + socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } + } + + + + public static CloseableHttpResponse doHttpsGet(String url, String data){ + enableSSL(); + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build(); + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfig).build(); + HttpGet httpGet = new HttpGet(url); + CloseableHttpResponse response = null; + try { + response = httpClient.execute(httpGet, context); + }catch (Exception e){ + e.printStackTrace(); + } + + return response; + } + + public static String toString(CloseableHttpResponse httpResponse) { + // 获取响应消息实体 + String result = null; + try { + HttpEntity entity = httpResponse.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity,"UTF-8"); + } + }catch (Exception e){}finally { + try { + httpResponse.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + public static Date getOutTime(int i) throws Exception { + Date rtn = null; + GregorianCalendar cal = new GregorianCalendar(); + Date date = new Date(); + cal.setTime(date); + cal.add(13, i); + rtn = cal.getTime(); + return rtn; + } + + + public static String getToken() throws Exception + { + + //return getToken( GET_TOKEN_URL, CorpID, SECRET); + + StringBuilder sb = new StringBuilder(); + sb.append("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="). + append(CorpID). + append("&corpsecret="). + append(SECRET); + String result = toString(doHttpsGet(sb.toString(), "")); + JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象 + JsonObject json = jsonparer.parse(result) + .getAsJsonObject(); + ACCESS_TOKEN = json.get("access_token").getAsString(); + outTime = getOutTime(json.get("expires_in").getAsInt()); + return json.get("access_token").getAsString(); + } + public static String getCurToken() throws Exception + { + Date now = new Date(); + long l = outTime.getTime()-now.getTime(); + if (l > 0) + return ACCESS_TOKEN; + return getToken(); + } + /** + * @desc 推送信息 + * @param token + * @param msg + * @return + */ + private static String sendMsgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}"; + + private static HttpClient webClient = null; + /** + * @desc 初始化创建 WebClient + */ + public static void initWebClient() { + + try { + PoolingClientConnectionManager tcm = new PoolingClientConnectionManager(); + tcm.setMaxTotal(10); + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + + } + + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + ctx.init(null, new X509TrustManager[] { tm }, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + Scheme sch = new Scheme("https", 443, ssf); + tcm.getSchemeRegistry().register(sch); + webClient = new DefaultHttpClient(tcm); + } catch (Exception ex) { + //log.error("initWebClient exception", ex); + } finally { + // log.info("initWebClient end...."); + } + } + + public static String sendMessage(String userid,String msg){ + try{ + getCurToken(); + //log.info("\n\nsendMessage start.token:"+token+",msg:"+msg); + String url = MessageFormat.format(sendMsgUrl, ACCESS_TOKEN); + HttpPost post = new HttpPost(url); + ResponseHandler responseHandler = new BasicResponseHandler(); + + //这里必须是一个合法的json格式数据,每个字段的意义可以查看上面连接的说明,content后面的test是要发送给用户的数据,这里是群发给所有人 + msg = msg = "{\"touser\":\"" + userid + "\",\"text\":{\"content\":\"" + msg + "\"},\"agentid\":\"1\",\"msgtype\":\"text\"}\""; + //msg = "{\"filter\":{\"is_to_all\":true},\"text\":{\"content\":\"test\"},\"msgtype\":\"text\"}\""; + + //设置发送消息的参数 + StringEntity entity = new StringEntity(msg,"UTF-8"); + + //解决中文乱码的问题 + //entity.setContentEncoding("UTF-8"); + entity.setContentType("application/json"); + post.setEntity(entity); + + //发送请求 + if (webClient==null) + initWebClient(); + String response = (String) webClient.execute(post, responseHandler); + return response; + + }catch (Exception e) { + return null; + } + } + + + + + + + +} + + diff --git a/selfDevelop/src/main/java/com/back/communication/mail/MailSenderInfo.java b/selfDevelop/src/main/java/com/back/communication/mail/MailSenderInfo.java new file mode 100644 index 0000000..d9dbc7e --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/mail/MailSenderInfo.java @@ -0,0 +1,115 @@ +package com.back.communication.mail; + +import java.util.Properties; + +public class MailSenderInfo { + // 发送邮件的服务器的IP和端口 + private String mailServerHost; + private String mailServerPort = "25"; + // 邮件发送者的地址 + private String fromAddress; + // 邮件接收者的地址 + private String toAddress; + // 登陆邮件发送服务器的用户名和密码 + private String userName; + private String password; + // 是否需要身份验证 + private boolean validate = false; + // 邮件主题 + private String subject; + // 邮件的文本内容 + private String content; + // 邮件附件的文件名 + private String[] attachFileNames; + + /** + * 获得邮件会话属性 + */ + public Properties getProperties() { + Properties p = new Properties(); + p.put("mail.smtp.host", this.mailServerHost); + p.put("mail.smtp.port", this.mailServerPort); + p.put("mail.smtp.auth", validate ? "true" : "false"); + return p; + } + + public String getMailServerHost() { + return mailServerHost; + } + + public void setMailServerHost(String mailServerHost) { + this.mailServerHost = mailServerHost; + } + + public String getMailServerPort() { + return mailServerPort; + } + + public void setMailServerPort(String mailServerPort) { + this.mailServerPort = mailServerPort; + } + + public boolean isValidate() { + return validate; + } + + public void setValidate(boolean validate) { + this.validate = validate; + } + + public String[] getAttachFileNames() { + return attachFileNames; + } + + public void setAttachFileNames(String[] fileNames) { + this.attachFileNames = fileNames; + } + + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getToAddress() { + return toAddress; + } + + public void setToAddress(String toAddress) { + this.toAddress = toAddress; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getContent() { + return content; + } + + public void setContent(String textContent) { + this.content = textContent; + } +} diff --git a/selfDevelop/src/main/java/com/back/communication/mail/MyAuthenticator.java b/selfDevelop/src/main/java/com/back/communication/mail/MyAuthenticator.java new file mode 100644 index 0000000..f810725 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/mail/MyAuthenticator.java @@ -0,0 +1,21 @@ +package com.back.communication.mail; + +import javax.mail.Authenticator; +import javax.mail.PasswordAuthentication; + +public class MyAuthenticator extends Authenticator { + String userName = null; + String password = null; + + public MyAuthenticator() { + } + + public MyAuthenticator(String username, String password) { + this.userName = username; + this.password = password; + } + + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(userName, password); + } +} diff --git a/selfDevelop/src/main/java/com/back/communication/mail/SimpleMailSender.java b/selfDevelop/src/main/java/com/back/communication/mail/SimpleMailSender.java new file mode 100644 index 0000000..a7de671 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/communication/mail/SimpleMailSender.java @@ -0,0 +1,110 @@ +package com.back.communication.mail; + +import java.util.Date; +import java.util.Properties; + +import javax.mail.Address; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; + +public class SimpleMailSender { + /** + * 以文本格式发送邮件 + * + * @param mailInfo + * @return + */ + public boolean sendTextMail(MailSenderInfo mailInfo) { + // 判断是否需要身份认证 + MyAuthenticator authenticator = null; + Properties pro = mailInfo.getProperties(); + if (mailInfo.isValidate()) { + // 如果需要身份认证,则创建一个密码验证器 + authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); + } + // 根据邮件会话属性和密码验证器构造一个发送邮件的session + Session sendMailSession = Session.getDefaultInstance(pro, authenticator); + try { + // 根据session创建一个邮件消息 + Message mailMessage = new MimeMessage(sendMailSession); + // 创建邮件发送者地址 + Address from = new InternetAddress(mailInfo.getFromAddress()); + // 设置邮件消息的发送者 + mailMessage.setFrom(from); + // 创建邮件的接收者地址,并设置到邮件消息中 + Address to = new InternetAddress(mailInfo.getToAddress()); + mailMessage.setRecipient(Message.RecipientType.TO, to); + // 设置邮件消息的主题 + mailMessage.setSubject(mailInfo.getSubject()); + // 设置邮件消息发送的时间 + mailMessage.setSentDate(new Date()); + // 设置邮件消息的主要内容 + String mailContent = mailInfo.getContent(); + mailMessage.setText(mailContent); + // 发送邮件 + Transport.send(mailMessage); + return true; + } catch (Exception ex) { + System.out.println(mailInfo.getToAddress() + " 发送失败:" + ex.getMessage()); + + } + return false; + } + + /** + * 以HTML格式发送邮件 + * + * @param mailInfo + * 待发送的邮件信息 + */ + public static boolean sendHtmlMail(MailSenderInfo mailInfo) { + // 判断是否需要身份认证 + MyAuthenticator authenticator = null; + Properties pro = mailInfo.getProperties(); + // 如果需要身份认证,则创建一个密码验证器 + if (mailInfo.isValidate()) { + authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); + } + // 根据邮件会话属性和密码验证器构造一个发送邮件的session + Session sendMailSession = Session.getDefaultInstance(pro, authenticator); + try { + // 根据session创建一个邮件消息 + Message mailMessage = new MimeMessage(sendMailSession); + // 创建邮件发送者地址 + Address from = new InternetAddress(mailInfo.getFromAddress()); + // 设置邮件消息的发送者 + mailMessage.setFrom(from); + // 创建邮件的接收者地址,并设置到邮件消息中 + Address to = new InternetAddress(mailInfo.getToAddress()); + // Message.RecipientType.TO属性表示接收者的类型为TO + mailMessage.setRecipient(Message.RecipientType.TO, to); + // 设置邮件消息的主题 + mailMessage.setSubject(mailInfo.getSubject()); + // 设置邮件消息发送的时间 + mailMessage.setSentDate(new Date()); + // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 + Multipart mainPart = new MimeMultipart(); + // 创建一个包含HTML内容的MimeBodyPart + BodyPart html = new MimeBodyPart(); + // 设置HTML内容 + html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); + mainPart.addBodyPart(html); + // 将MiniMultipart对象设置为邮件内容 + mailMessage.setContent(mainPart); + // 发送邮件 + Transport.send(mailMessage); + return true; + } catch (MessagingException ex) { + ex.printStackTrace(); + } + return false; + } +} diff --git a/selfDevelop/src/main/java/com/back/entity/Control.java b/selfDevelop/src/main/java/com/back/entity/Control.java new file mode 100644 index 0000000..583e976 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/entity/Control.java @@ -0,0 +1,292 @@ +package com.back.entity; + +public class Control implements java.io.Serializable { + + private String comid; + private String name; + private int lampid; + private int groupid; + private String terminal; + private int floorNo; + private String addr; + private Boolean iseffect; + private int id; + private String sign; + private Double longitude; + private Double latitude; + private int num; + private String barcode; + private int brightness; + private String mcontrol; + private String boxImage; + private String installImage; + private String worktype; + + private String tunnel; + private String protocol; + private String type; + private String remark; + private Boolean warningstate; + private Boolean controlstate; + + private Integer eventid; + private Boolean online; + private Boolean state; + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Control() { + } + + public Control(String comid, int lampId, int groupid, String terminal) { + this.comid = comid; + this.lampid = lampid; + this.groupid = groupid; + this.terminal = terminal; + } + + public int getBrightness() { + return brightness; + } + + public void setBrightness(int brightness) { + this.brightness = brightness; + } + + public String getMcontrol() { + return mcontrol; + } + + public void setMcontrol(String mcontrol) { + this.mcontrol = mcontrol; + } + + public String getBoxImage() { + return boxImage; + } + + public void setBoxImage(String boxImage) { + this.boxImage = boxImage; + } + + public String getInstallImage() { + return installImage; + } + + public void setInstallImage(String installImage) { + this.installImage = installImage; + } + + public Control(String comid, String name, int lampid, int groupid, String terminal, Boolean iseffect, + int brightness, String mcontrol, String worktype, String type, Boolean state, String protocol, + String tunnel, String remark, Boolean warningstate, Boolean controlstate, int eventid, Boolean online) { + this.comid = comid; + this.name = name; + this.lampid = lampid; + this.groupid = groupid; + this.terminal = terminal; + this.iseffect = iseffect; + this.worktype = worktype; + + this.type = type; + this.state = state; + this.remark = remark; + this.tunnel = tunnel; + this.protocol = protocol; + this.warningstate = warningstate; + this.controlstate = controlstate; + + this.eventid = eventid; + this.online = online; + } + + public String getWorktype() { + return worktype; + } + + public void setWorktype(String worktype) { + this.worktype = worktype; + } + + public String getComid() { + return this.comid; + } + + public void setComid(String comid) { + this.comid = comid; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public int getLampid() { + return lampid; + } + + public void setLampid(int lampid) { + this.lampid = lampid; + } + + public int getGroupid() { + return groupid; + } + + public void setGroupid(int groupid) { + this.groupid = groupid; + } + + public String getTerminal() { + return terminal; + } + + public void setTerminal(String terminal) { + this.terminal = terminal; + } + + public int getFloorNo() { + return floorNo; + } + + public void setFloorNo(int floorNo) { + this.floorNo = floorNo; + } + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } + + public Boolean getIseffect() { + return this.iseffect; + } + + public void setIseffect(Boolean iseffect) { + this.iseffect = iseffect; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getSign() { + return sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public int getNum() { + return num; + } + + public void setNum(int num) { + this.num = num; + } + + public String getBarcode() { + return barcode; + } + + public void setBarcode(String barcode) { + this.barcode = barcode; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getTunnel() { + return tunnel; + } + + public void setTunnel(String tunnel) { + this.tunnel = tunnel; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Boolean getControlstate() { + return controlstate; + } + + public void setControlstate(Boolean controlstate) { + this.controlstate = controlstate; + } + + public Boolean getWarningstate() { + return warningstate; + } + + public void setWarningstate(Boolean warningstate) { + this.warningstate = warningstate; + } + + public Integer getEventid() { + return eventid; + } + + public void setEventid(Integer eventid) { + this.eventid = eventid; + } + + public Boolean getOnline() { + return online; + } + + public void setOnline(Boolean online) { + this.online = online; + } + + public Boolean getState() { + return state; + } + + public void setState(Boolean state) { + this.state = state; + } +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/entity/Mcontrol.java b/selfDevelop/src/main/java/com/back/entity/Mcontrol.java new file mode 100644 index 0000000..f088ef8 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/entity/Mcontrol.java @@ -0,0 +1,338 @@ +package com.back.entity; + +// Generated Dec 8, 2010 3:23:36 PM by Hibernate Tools 3.2.2.GA + +/** + * Mcontrol generated by hbm2java + */ +public class Mcontrol implements java.io.Serializable { + + private int id; + private int num; + private String comid; + private String terminal; + private String name; + private int floorNo; + private String addr; + private Double longitude; + private Double latitude; + private String boxImage; + private String installImage; + private Integer sunrise; + private Integer sunset; + private String groups; + private String speed; + private String comport; + private String barcode; + private Boolean iseffect; + private String worktype; + + private Boolean active; + private Boolean iseffecttime; + private String destinetime; + private Float multiple; + + private String type; + private String tunnel; + private String protocol; + private String remark; + + private Boolean warningstate; + private Boolean controlstate; + private Boolean online; + private int ratio; + + public Float getMultiple() { + return multiple; + } + + public void setMultiple(Float multiple) { + this.multiple = multiple; + } + + public Boolean getUnderload() { + return underload; + } + + public void setUnderload(Boolean underload) { + this.underload = underload; + } + + private Boolean underload; + + public Mcontrol() { + } + + public Mcontrol(int id, int num, String comid, String terminal, String name, Double longitude, Double latitude, + Integer sunrise, Integer sunset, String groups, String speed, String comport, Boolean iseffect, + String worktype, Boolean active, Boolean iseffecttime, String destinetime, String type, String protocol, + String tunnel, String remark, Boolean warningstate, Boolean controlstate, Boolean online, int ratio) { + this.id = id; + this.num = num; + this.comid = comid; + this.terminal = terminal; + this.name = name; + this.longitude = longitude; + this.latitude = latitude; + this.sunrise = sunrise; + this.sunset = sunset; + this.groups = groups; + this.comport = comport; + this.speed = speed; + this.iseffect = iseffect; + this.worktype = worktype; + + this.active = active; + this.iseffecttime = iseffecttime; + this.destinetime = destinetime; + + this.type = type; + this.protocol = protocol; + this.tunnel = tunnel; + this.remark = remark; + this.warningstate = warningstate; + this.controlstate = controlstate; + this.online = online; + this.ratio = ratio; + } + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public Boolean getIseffecttime() { + return iseffecttime; + } + + public void setIseffecttime(Boolean iseffecttime) { + this.iseffecttime = iseffecttime; + } + + public String getDestinetime() { + return destinetime; + } + + public void setDestinetime(String destinetime) { + this.destinetime = destinetime; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public int getNum() { + return this.num; + } + + public void setNum(int num) { + this.num = num; + } + + public String getComid() { + return this.comid; + } + + public void setComid(String comid) { + this.comid = comid; + } + + public String getTerminal() { + return this.terminal; + } + + public void setTerminal(String terminal) { + this.terminal = terminal; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public int getFloorNo() { + return floorNo; + } + + public void setFloorNo(int floorNo) { + this.floorNo = floorNo; + } + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } + + public Double getLongitude() { + return this.longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public Double getLatitude() { + return this.latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public String getBoxImage() { + return boxImage; + } + + public void setBoxImage(String boxImage) { + this.boxImage = boxImage; + } + + public String getInstallImage() { + return installImage; + } + + public void setInstallImage(String installImage) { + this.installImage = installImage; + } + + public Integer getSunrise() { + return this.sunrise; + } + + public void setSunrise(Integer sunrise) { + this.sunrise = sunrise; + } + + public Integer getSunset() { + return this.sunset; + } + + public void setSunset(Integer sunset) { + this.sunset = sunset; + } + + public String getGroups() { + return this.groups; + } + + public void setGroups(String groups) { + this.groups = groups; + } + + public Boolean getIseffect() { + return this.iseffect; + } + + public void setIseffect(Boolean iseffect) { + this.iseffect = iseffect; + } + + public String getSpeed() { + return speed; + } + + public void setSpeed(String speed) { + this.speed = speed; + } + + public String getComport() { + return comport; + } + + public void setComport(String comport) { + this.comport = comport; + } + + public String getBarcode() { + return barcode; + } + + public void setBarcode(String barcode) { + this.barcode = barcode; + } + + public String getWorktype() { + return worktype; + } + + public void setWorktype(String worktype) { + this.worktype = worktype; + } + + public String getRemark() { + return this.remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getTunnel() { + return tunnel; + } + + public void setTunnel(String tunnel) { + this.tunnel = tunnel; + } + + public Boolean getControlstate() { + return controlstate; + } + + public void setControlstate(Boolean controlstate) { + this.controlstate = controlstate; + } + + public Boolean getWarningstate() { + return warningstate; + } + + public void setWarningstate(Boolean warningstate) { + this.warningstate = warningstate; + } + + public Boolean getOnline() { + return online; + } + + public void setOnline(Boolean online) { + this.online = online; + } + + public int getRatio() { + return ratio; + } + + public void setRatio(int ratio) { + this.ratio = ratio; + } +} diff --git a/selfDevelop/src/main/java/com/back/entity/Sensor.java b/selfDevelop/src/main/java/com/back/entity/Sensor.java new file mode 100644 index 0000000..e27bfc9 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/entity/Sensor.java @@ -0,0 +1,220 @@ +package com.back.entity; +// Generated Sep 1, 2010 2:01:42 PM by Hibernate Tools 3.2.2.GA + +/** + * City generated by hbm2java + */ +public class Sensor implements java.io.Serializable { + + + private int id; + private String name; + private String comid; + private String remark; + private Double longitude; + private Double latitude; + private String boxImage; + private String installImage; + private String tunnel; + private String protocol; + private String type; + private String worktype; + private String terminal; + private Boolean warningstate; + private Boolean controlstate; + private Boolean master; + private int num; + private int floorNo; + private String addr; + private int ratio; + private int cycle; + private int lane; + + public Sensor() { + } + + public Sensor(int id,String name,String comid,String tunnel,String protocol,String type,String worktype,int num,int ratio,int cycle,int lane, + String terminal,String remark,double longitude,double latitude,Boolean warningstate,Boolean controlstate,Boolean master) { + this.id = id; + this.name = name; + this.comid = comid; + this.tunnel = tunnel; + this.protocol = protocol; + this.type = type; + this.worktype = worktype; + this.num = num; + this.longitude = longitude; + this.latitude = latitude; + this.remark = remark; + this.terminal =terminal; + this.warningstate = warningstate; + this.controlstate = controlstate; + this.master = master; + this.ratio = ratio; + this.cycle = cycle; + this.lane = lane; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + public String getRemark() { + return this.remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public String getBoxImage() { + return boxImage; + } + + public void setBoxImage(String boxImage) { + this.boxImage = boxImage; + } + + public String getInstallImage() { + return installImage; + } + + public void setInstallImage(String installImage) { + this.installImage = installImage; + } + + public String getComid() { + return comid; + } + public void setComid(String comid) { + this.comid = comid; + } + + public String getProtocol() { + return protocol; + } + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + + public String getTunnel() { + return tunnel; + } + public void setTunnel(String tunnel) { + this.tunnel = tunnel; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + public String getWorktype() { + return worktype; + } + public void setWorktype(String worktype) { + this.worktype = worktype; + } + + public Boolean getControlstate() { + return controlstate; + } + public void setControlstate(Boolean controlstate) { + this.controlstate = controlstate; + } + + public Boolean getWarningstate() { + return warningstate; + } + public void setWarningstate(Boolean warningstate) { + this.warningstate = warningstate; + } + + public Boolean getMaster() { + return master; + } + public void setMaster(Boolean master) { + this.master = master; + } + + public int getNum() { + return num; + } + public void setNum(int num) { + this.num = num; + } + + public int getFloorNo() { + return floorNo; + } + + public void setFloorNo(int floorNo) { + this.floorNo = floorNo; + } + + public String getAddr() { + return addr; + } + + public void setAddr(String addr) { + this.addr = addr; + } + + public int getRatio() { + return ratio; + } + public void setRatio(int ratio) { + this.ratio = ratio; + } + + public int getCycle() { + return cycle; + } + public void setCycle(int cycle) { + this.cycle = cycle; + } + + public int getLane() { + return lane; + } + public void setLane(int lane) { + this.lane = lane; + } +} + + diff --git a/selfDevelop/src/main/java/com/back/entity/SyncEntity.java b/selfDevelop/src/main/java/com/back/entity/SyncEntity.java new file mode 100644 index 0000000..3b16fdb --- /dev/null +++ b/selfDevelop/src/main/java/com/back/entity/SyncEntity.java @@ -0,0 +1,49 @@ +package com.back.entity; + +public class SyncEntity { + + private String terminal; + private int controlsiseffect; + private int mcontrolsiseffect; + private int carsensorsiseffect; + private int luminancesensorsiseffect; + private int illuminationsensorsisEffect; + + public String getTerminal() { + return terminal; + } + public void setTerminal(String terminal) { + this.terminal = terminal; + } + public int getControlsiseffect() { + return controlsiseffect; + } + public void setControlsiseffect(int controlsiseffect) { + this.controlsiseffect = controlsiseffect; + } + public int getMcontrolsiseffect() { + return mcontrolsiseffect; + } + public void setMcontrolsiseffect(int mcontrolsiseffect) { + this.mcontrolsiseffect = mcontrolsiseffect; + } + public int getCarsensorsiseffect() { + return carsensorsiseffect; + } + public void setCarsensorsiseffect(int carsensorsiseffect) { + this.carsensorsiseffect = carsensorsiseffect; + } + public int getLuminancesensorsiseffect() { + return luminancesensorsiseffect; + } + public void setLuminancesensorsiseffect(int luminancesensorsiseffect) { + this.luminancesensorsiseffect = luminancesensorsiseffect; + } + public int getIlluminationsensorsisEffect() { + return illuminationsensorsisEffect; + } + public void setIlluminationsensorsisEffect(int illuminationsensorsisEffect) { + this.illuminationsensorsisEffect = illuminationsensorsisEffect; + } + +} diff --git a/selfDevelop/src/main/java/com/back/main/MainProcess.java b/selfDevelop/src/main/java/com/back/main/MainProcess.java new file mode 100644 index 0000000..000bfba --- /dev/null +++ b/selfDevelop/src/main/java/com/back/main/MainProcess.java @@ -0,0 +1,129 @@ +package com.back.main; + +import java.util.TimeZone; +import java.util.Timer; +import java.util.TimerTask; + +import com.back.action.Log; +import com.back.action.Work; +import com.back.common.RunParams; +import com.back.protocol.SystemParameter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MainProcess { + + public static final Logger LOGGER = LoggerFactory.getLogger(MainProcess.class); + private static Work work = new Work(); + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + + public static void main(String[] args) { + + // Wechat.sendMessage("wangwenbiao", + // "测试11[16020245]集中器下的1#组发生故障,故障内容为:灯具故障[000000621870]."); + // 2017 10 06 将主控开关的曲线数据保存过程,改成按时间点进行存储 + // 2017 10 14 将补抄任务独立出来 + // 1.1.50 完全使用多线程 + // 启动时,生成上一时刻的补抄任务 + // 1.1.51 增加久载状态更新 事件处理 + // 1.1.53 关闭监控线程 + // 1.1.54 处理保存慢的问题 + // 1.1.57 解决日志过大问题 + // 1.1.58 任务启动参数迁移到配置文件中 + // 1.1.59 关闭启动抄回路曲线操作 + // 1.2.03隧道光感增加传感器使能,使能状态保存在集中器基本信息中 + // 1.2.04 隧道光感 减少信道占用, 按光感变化阀值 及 上次是否成功 + // 1.2.06 使用系统默认的时区 + // 1.2.07 增加灯具日冻结 抄读命令(只抄当前的数据) + // 1.2.09 增加主控曲线转主控日冻结功能 + // 1.2.10 增加 隧道的电量计算,隧道异常电量分析 + // 1.2.11 简化通信管理机的业务流程,关闭定时巡测任务、传感器转发业务 + + System.out.println("ver 1.2.11 2019-03-24 17");// 英文 + + System.out.println(TimeZone.getDefault().getDisplayName()); + // 获取运行参数 + RunParams runParams = SystemParameter.GetPostParams(); + if (runParams == null) { + System.out.println("Database connection failed!"); + } + int Intervalscan = runParams.intervalScan; + int devideSyncTime = runParams.devideSyncTime; + + + /* GPRS指令转发处理 */ + Mythreadgprs mygprs = new Mythreadgprs(); + Thread gprs = new Thread(mygprs); + gprs.start(); + + + // 数据同步 + Timer dataSyncTimer = new Timer(); + dataSyncTimer.schedule(new TimerTask() { + public void run() { + work.DataSync(); + } + }, 0, devideSyncTime * 1000); + + + // 线程运行监控 + Timer timer3 = new Timer(); + timer3.schedule(new TimerTask() { + @Override + public void run() { + try { + work.RunScanThread();// 2017 11 11 如果 + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->timer3():" + e.getMessage()); + e.printStackTrace(); + } + } + }, 0, Intervalscan * 60 * 1000); + + + /* 上报事件处理 --事件处理 */ + Timer timerEvent = new Timer(); + timerEvent.schedule(new TimerTask() { + @Override + public void run() { + try { + work.RunEleAnalyzerData(); + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->timer():" + e.getMessage()); + e.printStackTrace(); + } + } + }, 0, 60 * 1000); + + + //定时日志 + Timer timelog = new Timer(); + timelog.schedule(new TimerTask() { + @Override + public void run() { + try { + Log.writelog(clazzName, "MainProcess Run!"); + } catch (Exception e) { + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->timer():" + e.getMessage()); + e.printStackTrace(); + } + } + }, 0, 30 * 1000); + + + } +} + + + + + diff --git a/selfDevelop/src/main/java/com/back/main/Mythreadgprs.java b/selfDevelop/src/main/java/com/back/main/Mythreadgprs.java new file mode 100644 index 0000000..4290893 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/main/Mythreadgprs.java @@ -0,0 +1,35 @@ +package com.back.main; + +import com.back.action.Log; +import com.back.action.Work; + +/** GPRS指令转发 工作线程 */ +public class Mythreadgprs implements Runnable { + private Work work = new Work(); + private String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + public void run() { + int i = 0; + while (true) { + + i++; + if (i > 600) { + i = 0; + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ForWardGprs() Run!"); + } + try { + Thread.sleep(100); + work.ForWardGprs(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/BusinessParameter.java b/selfDevelop/src/main/java/com/back/protocol/BusinessParameter.java new file mode 100644 index 0000000..40dac04 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/BusinessParameter.java @@ -0,0 +1,488 @@ +/*业务参数查询*/ +package com.back.protocol; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.jdbc.SQLHelper; + +public class BusinessParameter { + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /* + * 获取灯控器的条码号 + */ + public static String getbarcode(String ccomid) { + String strsql = "select barcode from controls where comid='" + ccomid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + String barcode = ""; + try { + while (rSet.next()) { + barcode = rSet.getString("barcode"); + } + } catch (SQLException e) { + Log.writelog(BusinessParameter.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return barcode; + } + + /** + * 根据灯装置序号查询灯控器地址 + * + * @param tcomid + * 终端地址 + * @param num + * 灯装置序号 + * @retrrn 灯通讯地址 + */ + public static String getCcomid(String tcomid, int num) { + String strsql = "SELECT comid FROM controls WHERE terminal='" + tcomid + "' AND num='" + num + + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + String result = ""; + try { + while (rSet.next()) { + result = rSet.getString("comid"); + } + } catch (SQLException e) { + System.out.println("Protocol.getCcomid():ERROR-->" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** 根据灯防盗序号查询灯控器地址 */ + public static String getCcomid(String tcomid, int gcomid, int lampid) { + String strsql = "SELECT comid FROM controls WHERE terminal='" + tcomid + "' AND GroupID='" + + gcomid + "' AND LampID=" + lampid; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + String result = ""; + try { + while (rSet.next()) { + result = rSet.getString("comid"); + } + } catch (SQLException e) { + Log.writelog(BusinessParameter.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** 2011-08-08:定采数据解析时使用主动上报故障数据更新定采数据 */ + public static String getEventInfoValue(String control, int type) { + String time = Common.getDateStr0(); + Date dt = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + dt = format.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + } + + String starttime = ""; + String endtime = ""; + GregorianCalendar gc = new GregorianCalendar(); + if (dt.getHours() < 12) { + gc.setTime(dt); + gc.add(5, -1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + starttime = format.format(gc.getTime()); + gc.add(5, 1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + endtime = format.format(gc.getTime()); + } else { + gc.setTime(dt); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + starttime = format.format(gc.getTime()); + gc.add(5, 1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + endtime = format.format(gc.getTime()); + } + format = null; + gc = null; + dt = null; + + String strrev = ""; + String strquery = "select eventid from eventinfo where control1='" + control + "' and type=" + + type + " and wtime>'" + starttime + "' and wtime<='" + endtime + "' "; + ResultSet rSet = SQLHelper.getResultSet(strquery); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + strrev = rSet.getString("eventid"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + try { + rSet.close(); + rSet = null; + } catch (Exception e) { + // TODO: handle exception + } + + return strrev; + } + + /** + * 根据终端地址,灯地址获取组地址 + * + * @param terminal + * 终端地址 + * @param ccomid + * 灯地址 + * @return string 组地址 + */ + public static int getgcomid(String terminal, String ccomid) { + int gcomid = 0; + + String strsql = "SELECT groupid FROM controls WHERE terminal='" + terminal + "' AND comid='" + + ccomid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return gcomid; + } + try { + while (rSet.next()) { + gcomid = rSet.getInt("groupid"); + } + } catch (SQLException e) { + Log.writelog(BusinessParameter.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return gcomid; + } + + /** 根据终端地址、组地址查询组名称 */ + public static String getgname(String tcomid, int gcomid) { + String result = ""; + String strsql = "SELECT name FROM groups WHERE terminal='" + tcomid + "' AND groupid=" + gcomid + + ""; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + result = rSet.getString("name"); + } + } catch (SQLException e) { + System.err.println("Protocal-->getGName->ERROR:" + e.toString()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + public static String getgname(String tcomid) { + String result = ""; + String strsql = "SELECT name FROM terminals WHERE comid='" + tcomid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + result = rSet.getString("name"); + } + } catch (SQLException e) { + System.err.println("Protocal-->getGName->ERROR:" + e.toString()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** 获取集中器所属线路 */ + public static String getLine(String terminal) { + String line = ""; + String strsql = "select line from terminals where comid='" + terminal + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + line = rSet.getString("line"); + } + } catch (Exception e) { + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return line; + } + + /** 按主控通信地址获取主控条码号 */ + public static String getMbarcode(String terminal, String mcomid) { + String barcode = ""; + String strsql = "select barcode from mcontrols where comid='" + mcomid + "' and terminal='" + + terminal + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + barcode = rSet.getString("barcode"); + } + } catch (SQLException e) { + Log.writelog(BusinessParameter.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + return barcode; + } + + /** + * 根据主控装置序号查询主控开关地址 + * + * @param tcomid + * 终端地址 + * @param num + * 灯装置序号 + * @retrrn 灯通讯地址 + */ + public static String getMcomid(String tcomid, int num) { + String result = ""; + + String strsql = "SELECT comid FROM mcontrols WHERE terminal='" + tcomid + "' AND num='" + num + + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + while (rSet.next()) { + result = rSet.getString("comid"); + } + } catch (SQLException e) { + System.err.println("Protocal-->getMcomid->ERROR:" + e.toString()); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 判断集中器是否设置短信发送处理 + * + * @param terminal + * 通信地址 + * @param informtype + * 发送信息类型 + */ + public static boolean IsSend(String terminal, String informtype) { + String line = getLine(terminal); + String strsql = "select count(1) from SmsInform where Line='" + line + "' and " + informtype + + "=1"; + if (SQLHelper.IsExist(strsql)) { + return true; + } else { + return false; + } + } + + /** + * 判断集中器是否设置短信发送处理 + * + * @param terminal + * 通信地址 + * @param informtype + * 发送信息类型 + */ + public static boolean IsSend(String terminal, int informtype) { + + String stringInformtype = "item19"; + switch (informtype) { + + case 1: // 温度预警 + stringInformtype = "item1"; + break; + case 2: // 漏电流预警 + stringInformtype = "item2"; + break; + case 3: // 相位不符预警 + stringInformtype = "item3"; + break; + case 4: // 线路不符警示 + stringInformtype = "item4"; + break; + case 5: // 台区不符警示 + stringInformtype = "item5"; + break; + case 6: // 使用寿命到期预警 + stringInformtype = "item6"; + break; + case 21: // 灯具故障 + stringInformtype = "item7"; + break; + case 22: // 温度故障 + stringInformtype = "item8"; + break; + case 23: // 超负荷报警 + stringInformtype = "item9"; + break; + case 24: // 功率因数过低 + stringInformtype = "item10"; + break; + case 25: // 时钟故障 + stringInformtype = "item11"; + break; + + /* + * case 41: //配电箱前门开启 stringInformtype = "item11"; break; case 42: //配电箱前门开启 stringInformtype = + * "item11"; break; + */ +/* + case 44: // 通迅异常 + stringInformtype = "item12"; + break;*/ + case 26: // 灯珠故障 + stringInformtype = "item13"; + break; + case 27: // 电源故障 + stringInformtype = "item14"; + break; + /* + * case 48: //传感器事件记录 stringInformtype = "item11"; break; + * + * + * case 111: //主控故障 A相电压超限 stringInformtype = "item12"; break; case 112: //主控故障 B相电压超限 + * stringInformtype = "item12"; break; case 113: //主控故障 C相电压超限 stringInformtype = "item12"; + * + * case 121: //主控故障 A相过载故障 stringInformtype = "item12"; break; case 122: //主控故障 B相过载故障 + * stringInformtype = "item12"; break; case 123: //主控故障 C相过载故障 stringInformtype = "item12"; + * break; + * + * + * case 131: //主控故障 A相 欠载故障 stringInformtype = "item12"; break; case 132: //主控故障 B相 欠载故障 + * stringInformtype = "item12"; break; case 133: //主控故障 C相 欠载故障 stringInformtype = "item12"; + * break; + * + * case 141: //主控故障 A相 功率因数过低 stringInformtype = "item12"; break; case 142: //主控故障 B相 功率因数过低 + * stringInformtype = "item12"; break; case 143: //主控故障 C相 功率因数过低 stringInformtype = "item12"; + * break; + * + * case 144: //交流接触器故障 stringInformtype = "item12"; break; + */ + } + Log.writelog(BusinessParameter.clazzName, "BusinessParameter->getLine start");//启动发送 + String line = getLine(terminal); + Log.writelog(BusinessParameter.clazzName, "BusinessParameter->getLine over");//启动发送 + String strsql = "select count(1) from SmsInform where Line='" + line + "' and " + + stringInformtype + "=1"; + if (SQLHelper.IsExist(strsql)) { + Log.writelog(BusinessParameter.clazzName, "BusinessParameter->issend over"); + return true; + } else { + Log.writelog(BusinessParameter.clazzName, "BusinessParameter->issend over"); + return false; + } + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/GW3761.java b/selfDevelop/src/main/java/com/back/protocol/GW3761.java new file mode 100644 index 0000000..0cf21fe --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/GW3761.java @@ -0,0 +1,3024 @@ +package com.back.protocol; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import com.back.action.Log; +import com.back.action.Work; +import com.back.common.Common; +import com.back.jdbc.SQLHelper; + +public class GW3761 extends Protocol { + // 控制域(从高位到低位):DIR(下行报文为0,上行报文为1);PRM(启动站发出为1,从动站发出为0);FCB(下行)/ACD(上行);FCV(下行);功能码 + // cdomain控制域(1个字节),adomain地址域(5个字节),afn应用层功能码(1个字节),seqdomain帧序列域(1个字节), + // pn测量点数(2个字节), fn功能码(2个字节),td_c曲线类数据时标(7个字节)GetAddMcontrolCmd + // pfc启动帧帧序号计数器(0~255) + + String cmdcode = ""; + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /** 处理曲线类数据 */ + public void CurveData(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String codeString = getCodeByTempmeter(taskidString); + String value = "", td_cnew; + String td_ctime = ""; + String[] array; + array = data.split("-"); + String meterCodeString = ""; + int offset = 0; + int succeedCount = 0; + while (offset < array.length) { + int pn1 = getPnOrFn(array[offset + 0], array[offset + 1], 0);// 信息点标识Pn + // int fn1 = getPnOrFn(array[offset + 2], array[offset + 3], 1);// + // 信息类标识Fn + String field = getField(fn); + meterCodeString = array[offset + 0] + array[offset + 1] + array[offset + 2] + array[offset + 3]; + offset += 4; + String td_c1 = array[offset + 0] + array[offset + 1] + array[offset + 2] + array[offset + 3] + + array[offset + 4]; // 曲线类数据时标中的(5字节) + // 分时日月年 + offset += 5; + + String td_c2 = array[offset + 0] + array[offset + 1];// 密度+点数 + offset += 2; + + meterCodeString = meterCodeString + td_c1 + td_c2; + + value = ""; + td_ctime = Common.formattime2(td_c1);// 分时日月年转为时间 + td_cnew = Common.timeadd(td_ctime, 0); + if (fn == 60) { // 回路曲线 + String avol = ""; + String bvol = ""; + String cvol = ""; + String acur = ""; + String bcur = ""; + String ccur = ""; + String Aactpow = ""; + String Bactpow = ""; + String Cactpow = ""; + String actpow = ""; + String areactpow = ""; + String breactpow = ""; + String creactpow = ""; + String reactpow = ""; + String aCos = ""; + String bCos = ""; + String cCos = ""; + String AKWh = ""; + String BKWh = ""; + String CKWh = ""; + String foract = ""; + + Log.writelog(GW3761.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->terminal:" + + adomain + " data:" + data); + // A相电压 + value = GeneralString.formatA07(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "avol", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + avol = value; + + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相电压 + value = GeneralString.formatA07(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "bvol", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + bvol = value; + + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相电压 + value = GeneralString.formatA07(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "cvol", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + cvol = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // A相电流 + value = GeneralString.formatA25(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "acur", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + acur = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相电流 + value = GeneralString.formatA25(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "bcur", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + bcur = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相电流 + value = GeneralString.formatA25(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "ccur", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + ccur = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // A相有功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "Aactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + Aactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相有功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "Bactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + Bactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相有功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "Cactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + Cactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // 总有功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "actpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + actpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + + // A相无功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "areactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + areactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相无功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "breactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + breactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相无功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "creactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + creactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + + // 无功功率 + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + offset += 3; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "reactpow", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + reactpow = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + + // A相功率因数 + value = GeneralString.formatA26(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "aCos", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + aCos = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相功率因数 + value = GeneralString.formatA26(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "bCos", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + bCos = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相功率因数 + value = GeneralString.formatA26(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "cCos", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + cCos = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + + // 功率因数 + value = GeneralString.formatA26(array[offset] + "-" + array[offset + 1]); + offset += 2; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "cCos", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + cCos = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + + // A相电能量 + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "AKWh", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + AKWh = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // B相电能量 + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "BKWh", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + BKWh = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // C相电能量 + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "CKWh", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + CKWh = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // 总电能 + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + if (!value.equals("")) { + // wdatas(adomain, pn1, td_cnew, "foract", value, + // batchtime);// 写曲线表 + if (value.toUpperCase().indexOf("F") == -1) + foract = value; + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + wdatas60(adomain, pn1, td_cnew, avol, bvol, cvol, acur, bcur, ccur, Aactpow, Bactpow, Cactpow, actpow, + areactpow, breactpow, creactpow, reactpow, aCos, bCos, cCos, AKWh, BKWh, CKWh, foract, + batchtime); + + // 主控开关状态------------------------------------------------------ + String Voltage = ""; + String electricity = ""; + actpow = ""; + String cos = ""; + foract = ""; + String LowFactorErr = ""; + String workState = ""; + String runState = ""; + String mstate = ""; + String mstate1 = ""; + String overvoltageErr = ""; + String LeakageErr = ""; + String overloadErr = ""; + int num = 0; + String underloadErr = ""; + String ControlErr = ""; + String LineErr = ""; + + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 工作状态:手自动 + workState = "1"; + else + workState = "0"; + if ((num & 0x02) > 1) // 运行方式 + runState = "1"; + else + runState = "0"; + if ((num & 0x04) > 1) // 继电器状态 + mstate = "1"; + else + mstate = "0"; + // 主控开关状态2 + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 交流接触器状态 + mstate1 = "1"; + else + mstate1 = "0"; + // 主控开关故障1 + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 电压超限 + overvoltageErr = "1"; + else + overvoltageErr = "0"; + if ((num & 0x02) > 1) // 功率因数过低 + LowFactorErr = "1"; + else + LowFactorErr = "0"; + if ((num & 0x04) > 1) // 漏电流过大 + LeakageErr = "1"; + else + LeakageErr = "0"; + if ((num & 0x08) > 1) // 过载 + overloadErr = "1"; + else + overloadErr = "0"; + + if ((num & 0x10) > 1) // 欠载 + underloadErr = "1"; + else + underloadErr = "0"; + + if ((num & 0x20) > 1) // 交流接触器故障 + ControlErr = "1"; + else + ControlErr = "0"; + if ((num & 0x40) > 1) // 线路故障 + LineErr = "1"; + else + LineErr = "0"; + // 主控开关故障2 + // num = Integer.parseInt(array[offset], 16); + offset++; + + // SQL 执行 + + String strsql = "Insert into mControlData(runtime,datatime,num,comid,terminal,name,actpow,Cos,Voltage,electricity,foract,workState,RunState,mstate,mstate1,overvoltageErr,LowFactorErr,LeakageErr,overloadErr,underloadErr,ControlErr,LineErr) " + + "select '" + Common.getDateStr0() + "','" + td_cnew + "',num,comid,terminal,name, '" + actpow + + "'," + "'" + cos + "','" + Voltage + "','" + electricity + "','" + foract + "'," + workState + + "," + runState + "," + mstate + "," + mstate1 + "," + overvoltageErr + "," + LowFactorErr + + "," + LeakageErr + "," + overloadErr + "," + underloadErr + "," + ControlErr + "," + LineErr + + " from mcontrols where terminal='" + adomain + "' and num=" + Integer.toString(pn1); + + SQLHelper.ExecSql(strsql); + // 主控开关故障v----------------------------------------------------- + } else if (fn == 101 || fn == 102 || fn == 103 || fn == 104) { + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + + if (!value.equals("")) { + wdatas(adomain, pn1, td_cnew, field, value, batchtime);// 写曲线表 + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + // Protocol.deltempmeters(taskidString);// 删除补抄表记录 + offset += 4; + continue; + } else if (fn == 101 || fn == 102 || fn == 103 || fn == 104) { + value = GeneralString.formatA11( + array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + if (!value.equals("")) { + wdatas(adomain, pn1, td_cnew, field, value, batchtime);// 写曲线表 + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + offset += 4; + continue; + } else if (fn == 81 || fn == 85 || fn == 92 || fn == 93 || fn == 94 || fn == 95) { + if (fn == 81 || fn == 85) { + value = GeneralString.formatA09(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + } else if (fn == 92 || fn == 93 || fn == 94 || fn == 95) { + value = GeneralString.formatA25(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2]); + } + if (!value.equals("")) { + wdatas(adomain, pn1, td_cnew, field, value, batchtime);// 写曲线表 + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + offset += 3; + continue; + } else if (fn == 89 || fn == 90 || fn == 91 || fn == 105) { + value = GeneralString.formatA07(array[offset] + "-" + array[offset + 1]); + if (!value.equals("")) { + wdatas(adomain, pn1, td_cnew, field, value, batchtime);// 写曲线表 + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + } + offset += 2; + continue; + } + if (codeString.equals("")) { + Protocol.deltempmeters(taskidString); + } else { + if (succeedCount > 0) + UpdateCodeByTempmeter(taskidString, codeString); + } + } // while (data.length()>4) + } + + /** + * 灯控器巡测数据 -主动上报 + * + * @param data + * @param adomain + * @param pn + * @param fn + * @param batchtime + * @param taskidString + */ + public void FreezeDataF6(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String[] array; + array = data.split("-"); + int offset = 0; + String Voltage = ""; + String electricity = ""; + String actpow = ""; + String temperatureWarning = ""; + String LeakageWarning = ""; + String PhaseWarning = ""; + String LineWarning = ""; + String AreaWarning = ""; + String LifeTimeWarning = ""; + String lamperr = ""; + String temperatureerr = ""; + String overloaderr = ""; + String LowFactorErr = ""; + String clockerr = ""; + String Aafferr = ""; + String Bafferr = ""; + String Cafferr = ""; + String worktype = ""; + String controlState = ""; + String TimingState = ""; + + String runState = ""; + String lederr = ""; + String powererr = ""; + + int num = 0; + while (offset < array.length) { + int pn1 = getPnOrFn(array[offset + 0], array[offset + 1], 0);// 信息点标识Pn + // int fn1 = getPnOrFn(array[offset + 2], array[offset + 3], 1);// + // 信息类标识Fn + offset += 4; + // 电压 + Voltage = GeneralString.formatA07(array[offset + 0] + array[offset + 1]); + offset += 2; + // 电流 + Voltage = GeneralString.formatA06(array[offset + 0] + array[offset + 1]); + electricity += 2; + // 有功功率 + actpow = GeneralString + .formatA13(array[offset + 0] + array[offset + 1] + array[offset + 2] + array[offset + 3]); + offset += 4; + // 灯控器故障2(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x04) > 1) // 温度预警 + temperatureWarning = "1"; + else + temperatureWarning = "0"; + if ((num & 0x08) > 1) // 漏电流预警 + LeakageWarning = "1"; + else + LeakageWarning = "0"; + + if ((num & 0x10) > 1) // 相位不符 + PhaseWarning = "1"; + else + PhaseWarning = "0"; + if ((num & 0x20) > 1) // 线路不符 + LineWarning = "1"; + else + LineWarning = "0"; + if ((num & 0x40) > 1) // 台区不符 + AreaWarning = "1"; + else + AreaWarning = "0"; + if ((num & 0x80) > 1) // 使用寿命到期 + LifeTimeWarning = "1"; + else + LifeTimeWarning = "0"; + + // 灯控器故障1(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 灯具故障 + lamperr = "1"; + else + lamperr = "0"; + if ((num & 0x02) > 1) // 温度故障 + temperatureerr = "1"; + else + temperatureerr = "0"; + if ((num & 0x04) > 1) // 超负荷报警 + overloaderr = "1"; + else + overloaderr = "0"; + if ((num & 0x10) > 1) // 功率因数过低 + LowFactorErr = "1"; + else + LowFactorErr = "0"; + if ((num & 0x20) > 1) // 灯珠故障 + lederr = "1"; + else + lederr = "0"; + if ((num & 0x40) > 1) // 时钟故障 + clockerr = "1"; + else + clockerr = "0"; + if ((num & 0x80) > 1) // 电源故障 + powererr = "1"; + else + powererr = "0"; + // 灯控器状态2(状态字) + num = Integer.parseInt(array[offset], 16); + offset++; + + if ((num & 0x01) > 1) // A相归属错误 + Aafferr = "1"; + else + Aafferr = "0"; + if ((num & 0x02) > 1) // B相归属错误 + Bafferr = "1"; + else + Bafferr = "0"; + if ((num & 0x04) > 1) // C相归属错误 + Cafferr = "1"; + else + Cafferr = "0"; + // 灯控器状态1(状态字) + num = Integer.parseInt(array[offset], 16); + offset++; + worktype = Common.dec2Hex(num & 0x3, 2); + if ((num & 0x04) > 1) // C控制状态 + controlState = "1"; + else + controlState = "0"; + if ((num & 0x08) > 1) // 请求校时状态 + TimingState = "1"; + else + TimingState = "0"; + + // SQL 执行 + String strsql = "Insert into lampdata(runtime,datatime,terminal,barcode,groupid,control,Voltage,electricity,actpow,worktype,temperatureWarning,LeakageWarning,PhaseWarning,LineWarning,AreaWarning,LifeTimeWarning,lamperr,temperatureerr,overloaderr,LowFactorErr,clockerr,Aafferr,Bafferr,Cafferr,controlState,TimingState,lederr,powererr,runState) " + + "select '" + Common.getDateStr0() + "','" + Common.getYesterdayStr7() + + "',terminal,barcode,GroupID,comid, '" + Voltage + "'," + "'" + electricity + "','" + actpow + + "','" + worktype + "'," + temperatureWarning + "," + LeakageWarning + "," + PhaseWarning + "," + + LineWarning + "," + AreaWarning + "," + LifeTimeWarning + "," + lamperr + "," + temperatureerr + + "," + overloaderr + "," + LowFactorErr + "," + clockerr + "," + Aafferr + "," + Bafferr + "," + + Cafferr + "," + controlState + "," + TimingState + "," + lederr + "," + powererr + "," + runState + + " from controls where terminal='" + adomain + "' and num=" + Integer.toString(pn1); + SQLHelper.ExecSql(strsql); + } // while (offset < array.length) + + Protocol.deltempmeters(taskidString); + } + + /** + * 灯控器巡测数据 -主动上报 + * + * @param data + * @param adomain + * @param pn + * @param fn + * @param batchtime + * @param taskidString + */ + public void FreezeDataF7(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String[] array; + array = data.split("-"); + int offset = 4; + String Voltage = ""; + String electricity = ""; + String actpow = ""; + String temperatureWarning = ""; + String LeakageWarning = ""; + String PhaseWarning = ""; + String LineWarning = ""; + String AreaWarning = ""; + String LifeTimeWarning = ""; + String lamperr = ""; + String temperatureerr = ""; + String overloaderr = ""; + String LowFactorErr = ""; + String clockerr = ""; + String Aafferr = "0"; + String Bafferr = "0"; + String Cafferr = "0"; + String worktype = ""; + String controlState = ""; + String TimingState = ""; + String Dimming = ""; + String temperature = ""; + + String runState = ""; + String lederr = ""; + String powererr = ""; + int num = 0; + int lampCount = Integer.valueOf(array[offset], 16); + offset++; + while (offset < array.length) { + // 测量点编号 + int pn1 = Integer.valueOf(array[offset + 1] + array[offset + 0], 16);// 信息点标识Pn + offset += 2; + // 电压 + Voltage = GeneralString.formatA260(array[offset + 0] + "-" + array[offset + 1]); + offset += 2; + // 电流 + electricity = GeneralString.formatA06(array[offset + 0] + "-" + array[offset + 1]); + offset += 2; + // 有功功率 + actpow = GeneralString.formatA261( + array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + + num = Integer.parseInt(array[offset], 16); + runState = String.valueOf(num); + offset++;// 未用 + // 灯控器状态1(状态字) + num = Integer.parseInt(array[offset], 16); + offset++; + worktype = Common.dec2Hex(num & 0x3, 2); + if ((num & 0x04) > 1) // C控制状态 + controlState = "1"; + else + controlState = "0"; + if ((num & 0x08) > 1) // 请求校时状态 + TimingState = "1"; + else + TimingState = "0"; + + // 灯控器故障1(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 0) // 灯具故障 + lamperr = "1"; + else + lamperr = "0"; + if ((num & 0x02) > 1) // 温度故障 + temperatureerr = "1"; + else + temperatureerr = "0"; + if ((num & 0x04) > 1) // 超负荷报警 + overloaderr = "1"; + else + overloaderr = "0"; + if ((num & 0x10) > 1) // 功率因数过低 + LowFactorErr = "1"; + else + LowFactorErr = "0"; + if ((num & 0x40) > 1) // 灯珠故障 + lederr = "1"; + else + lederr = "0"; + if ((num & 0x10) > 1) // 时钟故障 + clockerr = "1"; + else + clockerr = "0"; + if ((num & 0x80) > 1) // 电源故障 + powererr = "1"; + else + powererr = "0"; + // 灯控器故障2(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x04) > 1) // 温度预警 + temperatureWarning = "1"; + else + temperatureWarning = "0"; + if ((num & 0x08) > 1) // 漏电流预警 + LeakageWarning = "1"; + else + LeakageWarning = "0"; + + if ((num & 0x10) > 1) // 相位不符 + PhaseWarning = "1"; + else + PhaseWarning = "0"; + if ((num & 0x20) > 1) // 线路不符 + LineWarning = "1"; + else + LineWarning = "0"; + if ((num & 0x40) > 1) // 台区不符 + AreaWarning = "1"; + else + AreaWarning = "0"; + if ((num & 0x80) > 1) // 使用寿命到期 + LifeTimeWarning = "1"; + else + LifeTimeWarning = "0"; + + // 灯控器状态2(状态字) + // num = Integer.parseInt(array[offset], 16); + // offset++; + /* + * if ((num & 0x01) > 1) // A相归属错误 Aafferr = "1"; else Aafferr = + * "0"; if ((num & 0x02) > 1) // B相归属错误 Bafferr = "1"; else Bafferr + * = "0"; if ((num & 0x04) > 1) // C相归属错误 Cafferr = "1"; else + * Cafferr = "0"; + */ + // 调光值 + Dimming = String.valueOf(Integer.parseInt(array[offset], 16)); + offset++; + // temperature = String.valueOf(Integer.valueOf(array[offset + + // 1]+array[offset + 0], 16)); + temperature = String.valueOf(Integer.valueOf(array[offset + 0], 10)); + if (Integer.valueOf(array[offset + 1], 10) > 1) + temperature = "-" + temperature; + offset += 2; + // 温度 + // 抄读最近一次日期 + String datatime = GeneralString.formatA17( + array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + // 获取 灯控器信息 + String terminal = adomain; + String barcode = ""; + String GroupID = "0"; + String comid = ""; + String strsql = "select comid,barcode,GroupID from controls where terminal='" + adomain + "' and num=" + + String.valueOf(pn1); + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet != null) { + try { + while (rSet.next()) { + barcode = rSet.getString("barcode"); + GroupID = rSet.getString("GroupID"); + comid = rSet.getString("comid"); + } + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + // SQL 执行 + strsql = "Insert into lampdata(Dimming,temperature,num,runtime,datatime,terminal,barcode,groupid,control,Voltage,electricity,actpow,worktype,temperatureWarning,LeakageWarning,PhaseWarning,LineWarning,AreaWarning,LifeTimeWarning,lamperr,temperatureerr,overloaderr,LowFactorErr,clockerr,Aafferr,Bafferr,Cafferr,controlState,TimingState,LEDerr,Powererr,runState) " + + "select " + "'" + Dimming + "'," + "'" + temperature + "'," + Integer.toString(pn1) + ",'" + + Common.getDateStr0() + "','" + datatime + "',terminal,barcode,GroupID,comid, '" + Voltage + "'," + + "'" + electricity + "','" + actpow + "','" + worktype + "'," + temperatureWarning + "," + + LeakageWarning + "," + PhaseWarning + "," + LineWarning + "," + AreaWarning + "," + + LifeTimeWarning + "," + lamperr + "," + temperatureerr + "," + overloaderr + "," + LowFactorErr + + "," + clockerr + "," + Aafferr + "," + Bafferr + "," + Cafferr + "," + controlState + "," + + TimingState + "," + lederr + "," + powererr + "," + runState + " from controls where terminal='" + + adomain + "' and num=" + Integer.toString(pn1); + SQLHelper.ExecSql(strsql); + // 事件处理 + + /* + * if (lamperr.equals("1")) wEventInfo("21", terminal, GroupID, + * comid, barcode); else if (temperatureerr.equals("1")) + * wEventInfo("1", terminal, GroupID, comid, barcode); else if + * (overloaderr.equals("1")) wEventInfo("23", terminal, GroupID, + * comid, barcode); else if (LowFactorErr.equals("1")) + * wEventInfo("24", terminal, GroupID, comid, barcode); else if + * (clockerr.equals("1")) wEventInfo("25", terminal, GroupID, comid, + * barcode); else if (LifeTimeWarning.equals("1")) wEventInfo("6", + * terminal, GroupID, comid, barcode); else if + * (LeakageWarning.equals("1")) wEventInfo("2", terminal, GroupID, + * comid, barcode); + */ + // 事件处理 + } // while (offset < array.length) + + // Protocol.deltempmeters(taskidString); + } + + /** + * 色温灯控器巡测数据 -主动上报 + * + * @param data + * @param adomain + * @param pn + * @param fn + * @param batchtime + * @param taskidString + */ + public void FreezeDataF9(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String[] array; + array = data.split("-"); + int offset = 4; + String Voltage = ""; + String electricity = ""; + String actpow = ""; + String temperatureWarning = ""; + String LeakageWarning = ""; + String PhaseWarning = ""; + String LineWarning = ""; + String AreaWarning = ""; + String LifeTimeWarning = ""; + String lamperr = ""; + String temperatureerr = ""; + String overloaderr = ""; + String LowFactorErr = ""; + String clockerr = ""; + String Aafferr = "0"; + String Bafferr = "0"; + String Cafferr = "0"; + String worktype = ""; + String controlState = ""; + String TimingState = ""; + String DimmingR = ""; + String DimmingG = ""; + String DimmingB = ""; + String temperature = ""; + int num = 0; + int lampCount = Integer.valueOf(array[offset], 16); + offset++; + while (offset < array.length) { + // 测量点编号 + int pn1 = Integer.valueOf(array[offset + 1] + array[offset + 0], 16);// 信息点标识Pn + offset += 2; + // 电压 + Voltage = GeneralString.formatA260(array[offset + 0] + "-" + array[offset + 1]); + offset += 2; + // 电流 + electricity = GeneralString.formatA06(array[offset + 0] + "-" + array[offset + 1]); + offset += 2; + // 有功功率 + actpow = GeneralString.formatA261( + array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + + offset++;// 未用 + // 灯控器状态1(状态字) + num = Integer.parseInt(array[offset], 16); + offset++; + worktype = Common.dec2Hex(num & 0x3, 2); + if ((num & 0x04) > 1) // C控制状态 + controlState = "1"; + else + controlState = "0"; + if ((num & 0x08) > 1) // 请求校时状态 + TimingState = "1"; + else + TimingState = "0"; + // 灯控器故障2(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x04) > 1) // 温度预警 + temperatureWarning = "1"; + else + temperatureWarning = "0"; + if ((num & 0x08) > 1) // 漏电流预警 + LeakageWarning = "1"; + else + LeakageWarning = "0"; + + if ((num & 0x10) > 1) // 相位不符 + PhaseWarning = "1"; + else + PhaseWarning = "0"; + if ((num & 0x20) > 1) // 线路不符 + LineWarning = "1"; + else + LineWarning = "0"; + if ((num & 0x40) > 1) // 台区不符 + AreaWarning = "1"; + else + AreaWarning = "0"; + if ((num & 0x80) > 1) // 使用寿命到期 + LifeTimeWarning = "1"; + else + LifeTimeWarning = "0"; + + // 灯控器故障1(故障字) + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 灯具故障 + lamperr = "1"; + else + lamperr = "0"; + if ((num & 0x02) > 1) // 温度故障 + temperatureerr = "1"; + else + temperatureerr = "0"; + if ((num & 0x04) > 1) // 超负荷报警 + overloaderr = "1"; + else + overloaderr = "0"; + if ((num & 0x10) > 1) // 功率因数过低 + LowFactorErr = "1"; + else + LowFactorErr = "0"; + if ((num & 0x40) > 1) // 时钟故障 + clockerr = "1"; + else + clockerr = "0"; + + // 灯控器状态2(状态字) + // num = Integer.parseInt(array[offset], 16); + // offset++; + /* + * if ((num & 0x01) > 1) // A相归属错误 Aafferr = "1"; else Aafferr = + * "0"; if ((num & 0x02) > 1) // B相归属错误 Bafferr = "1"; else Bafferr + * = "0"; if ((num & 0x04) > 1) // C相归属错误 Cafferr = "1"; else + * Cafferr = "0"; + */ + // 色温1调光值 + DimmingR = String.valueOf(Integer.parseInt(array[offset], 16)); + offset++; + // 色温2调光值 + DimmingG = String.valueOf(Integer.parseInt(array[offset], 16)); + offset++; + // 色温3调光值 + DimmingB = String.valueOf(Integer.parseInt(array[offset], 16)); + offset++; + + // temperature = String.valueOf(Integer.valueOf(array[offset + + // 1]+array[offset + 0], 16)); + temperature = String.valueOf(Integer.valueOf(array[offset + 0], 10)); + if (Integer.valueOf(array[offset + 1], 10) > 1) + temperature = "-" + temperature; + offset += 2; + // 温度 + // 抄读最近一次日期 + String datatime = GeneralString.formatA17( + array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + // 获取 灯控器信息 + String terminal = adomain; + String barcode = ""; + String GroupID = "0"; + String comid = ""; + String strsql = "select comid,barcode,GroupID from controls where terminal='" + adomain + "' and num=" + + String.valueOf(pn1); + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet != null) { + try { + while (rSet.next()) { + barcode = rSet.getString("barcode"); + GroupID = rSet.getString("GroupID"); + comid = rSet.getString("comid"); + } + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + // SQL 执行 + strsql = "Insert into lampdata(Dimming,Dimming2,Dimming3,temperature,num,runtime,datatime,terminal,barcode,groupid,control,Voltage,electricity,actpow,worktype,temperatureWarning,LeakageWarning,PhaseWarning,LineWarning,AreaWarning,LifeTimeWarning,lamperr,temperatureerr,overloaderr,LowFactorErr,clockerr,Aafferr,Bafferr,Cafferr,controlState,TimingState) " + + "select " + "'" + DimmingR + "'," + "'" + DimmingG + "'," + "'" + DimmingB + "'," + "'" + + temperature + "'," + Integer.toString(pn1) + ",'" + Common.getDateStr0() + "','" + datatime + + "',terminal,barcode,GroupID,comid, '" + Voltage + "'," + "'" + electricity + "','" + actpow + + "','" + worktype + "'," + temperatureWarning + "," + LeakageWarning + "," + PhaseWarning + "," + + LineWarning + "," + AreaWarning + "," + LifeTimeWarning + "," + lamperr + "," + temperatureerr + + "," + overloaderr + "," + LowFactorErr + "," + clockerr + "," + Aafferr + "," + Bafferr + "," + + Cafferr + "," + controlState + "," + TimingState + " from controls where terminal='" + adomain + + "' and num=" + Integer.toString(pn1); + SQLHelper.ExecSql(strsql); + // 事件处理 + + if (lamperr.equals("1")) + wEventInfo("21", terminal, GroupID, comid, barcode); + else if (temperatureerr.equals("1")) + wEventInfo("1", terminal, GroupID, comid, barcode); + else if (overloaderr.equals("1")) + wEventInfo("23", terminal, GroupID, comid, barcode); + else if (LowFactorErr.equals("1")) + wEventInfo("24", terminal, GroupID, comid, barcode); + else if (clockerr.equals("1")) + wEventInfo("25", terminal, GroupID, comid, barcode); + else if (LifeTimeWarning.equals("1")) + wEventInfo("6", terminal, GroupID, comid, barcode); + else if (LeakageWarning.equals("1")) + wEventInfo("2", terminal, GroupID, comid, barcode); + + // 事件处理 + } // while (offset < array.length) + + // Protocol.deltempmeters(taskidString); + } + + /** + * + * @param eType + * 事件类型 + * @param terminal + * 集中器通信地址 + * @param GroupID + * 组号 + * @param comid + * 灯控器通信地址 + * @param barcode + * 灯控器出厂编号 + */ + private void wEventInfo(String eType, String terminal, String GroupID, String comid, String barcode) { + + String strsql = "insert into EventInfo(wtime,terminal,groupid,control1,barcode1,[type],counttime) " + + " values( '" + Common.getDateStr0() + "'," + "'" + terminal + "'," + GroupID + "," + "'" + comid + + "'," + "'" + barcode + "'," + "'" + eType + "'," + "'" + Common.getDateStr0() + "'" + ")"; + SQLHelper.ExecSql(strsql); + } + + /** + * 昨日正向有功电能量 + * + * @param data + * @param adomain + * @param pn + * @param fn + * @param batchtime + * @param taskidString + */ + public void FreezeDataF41(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String[] array; + array = data.split("-"); + int offset = 4; + int num = 0; + String strKWh = ""; + String SQL = ""; + + // 获取集中器信息 + String line = ""; + int multiple = 1; + int digit = 6; + int rowCount = 0; + String types = "0002"; + SQL = "select multiple,line from terminals where comid='" + adomain + "'"; + ResultSet rSet = SQLHelper.getResultSet(SQL); + if (rSet != null) { + try { + while (rSet.next()) { + line = rSet.getString("line"); + multiple = rSet.getInt("multiple"); + } + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + String YessterdayString = Common.getYesterdayStr7(); + String nowString = Common.getDateStr0(); + while (offset < array.length) { + // 正向有功总 + strKWh = GeneralString.formatA11( + array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + num++; + if (num == 1) {// 日冻结数据 daydatas + SQL = "select count(terminal) num from daydatas where terminal='" + adomain + "' and datadate='" + + YessterdayString + "'"; + rSet = SQLHelper.getResultSet(SQL); + if (rSet != null) { + try { + while (rSet.next()) { + rowCount = rSet.getInt("num"); + } + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (rowCount == 0) { + SQL = "insert into daydatas(circuitry,terminal,multiple,digit,types,foract,Computertime,foracttime,datadate,succeed,comid)" + + " values(" + "'" + line + "'," + "'" + adomain + "'," + String.valueOf(multiple) + "," + + String.valueOf(digit) + "," + "'" + types + "'," + "'" + strKWh + "'," + "'" + nowString + + "'," + "'" + YessterdayString + " 00:00:00" + "'," + "'" + YessterdayString + "'," + + "'1'," + "'" + adomain + "'" + ")"; + SQLHelper.ExecSql(SQL); + // 计算发生电量 + SQL = "select foract from daydatas where terminal = '" + adomain + "' and foracttime<'" + + YessterdayString + "'"; + rSet = SQLHelper.getResultSet(SQL); + double foract1 = 0.0; + if (rSet != null) { + try { + while (rSet.next()) { + foract1 = rSet.getDouble("foract"); + } + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + double dKWh = Double.valueOf(strKWh); + if (foract1 > dKWh) // 处理过周 (happen IS NULL OR + // len(happen)=0) and + SQL = "update daydatas set happen= " + " isnull(" + + " (100000 + cast(foract as decimal)-(SELECT max(cast(foract as decimal)) " + + " FROM daydatas WHERE foracttime 1) // 工作状态:手自动 + workState = "1"; + else + workState = "0"; + if ((num & 0x02) > 1) // 运行方式 + runState = "1"; + else + runState = "0"; + if ((num & 0x04) > 1) // 继电器状态 + mstate = "1"; + else + mstate = "0"; + // 主控开关状态2 + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 交流接触器状态 + mstate1 = "1"; + else + mstate1 = "0"; + // 主控开关故障1 + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 1) // 电压超限 + overvoltageErr = "1"; + else + overvoltageErr = "0"; + if ((num & 0x02) > 1) // 功率因数过低 + LowFactorErr = "1"; + else + LowFactorErr = "0"; + if ((num & 0x04) > 1) // 漏电流过大 + LeakageErr = "1"; + else + LeakageErr = "0"; + if ((num & 0x08) > 1) // 过载 + overloadErr = "1"; + else + overloadErr = "0"; + + if ((num & 0x10) > 1) // 欠载 + underloadErr = "1"; + else + underloadErr = "0"; + + if ((num & 0x20) > 1) // 交流接触器故障 + ControlErr = "1"; + else + ControlErr = "0"; + if ((num & 0x40) > 1) // 线路故障 + LineErr = "1"; + else + LineErr = "0"; + // 主控开关故障2 + // num = Integer.parseInt(array[offset], 16); + offset++; + + // SQL 执行 + + String strsql = "Insert into mControlData(rruntime,datatime,num,comid,terminal,name,actpow,Cos,Voltage,electricity,foract,workState,RunState,mstate,mstate1,overvoltageErr,LowFactorErr,LeakageErr,overloadErr,underloadErr,ControlErr,LineErr) " + + "select '" + Common.getDateStr0() + "','" + td_cnew + "',num,comid,terminal,name, '" + actpow + + "'," + "'" + cos + "','" + Voltage + "','" + electricity + "','" + foract + "'," + workState + + "," + runState + "," + mstate + "," + mstate1 + "," + overvoltageErr + "," + LowFactorErr + + "," + LeakageErr + "," + overloadErr + "," + underloadErr + "," + ControlErr + "," + LineErr + + " from mcontrols where terminal='" + adomain + "' and num=" + Integer.toString(pn1); + + SQLHelper.ExecSql(strsql); + } // for (int i = 0; i < rowCount; i++) + + } // while (offset < array.length) + + Protocol.deltempmeters(taskidString); + } + + public void CurveDataLamp(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String td_ctime = ""; + String[] array; + array = data.split("-"); + int offset = 0; + td_ctime = Common.getYesterdayStr7() + " 00:00:00";// 分时日月年转为时间 + while (offset < array.length) { + int pn1 = getPnOrFn(array[offset + 0], array[offset + 1], 0);// 信息点标识Pn + // int fn1 = getPnOrFn(array[offset + 2], array[offset + 3], 1);// + // 信息类标识Fn + offset = offset + 4; + + String[] dataStrings = new String[4]; + // td_ctime = Common.timeadd(td_ctime, 15); + + switch (fn) { + + case 25:// 昨天A、B、C相及有功功率 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString + .formatA09(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + dataStrings[1] = GeneralString + .formatA09(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + dataStrings[2] = GeneralString + .formatA09(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + case 31:// 昨天总功率因数/三相功率因数 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString.formatA26(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + dataStrings[1] = GeneralString.formatA26(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + dataStrings[2] = GeneralString.formatA26(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + dataStrings[3] = GeneralString.formatA26(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + case 33:// 昨天总有功功率 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString + .formatA09(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + + case 35:// 昨天三相电压 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString.formatA07(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + dataStrings[1] = GeneralString.formatA07(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + dataStrings[2] = GeneralString.formatA07(array[offset + 0] + '-' + array[offset + 1]); + offset += 2; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + case 38:// 昨天三相电流 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString + .formatA25(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + dataStrings[1] = GeneralString + .formatA25(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + dataStrings[2] = GeneralString + .formatA25(array[offset + 0] + '-' + array[offset + 1] + '-' + array[offset + 2]); + offset += 3; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + case 41:// 昨日正向有功电能量 + for (int i = 0; i < 96; i++) { + dataStrings[0] = GeneralString.formatA11(array[offset + 0] + '-' + array[offset + 1] + '-' + + array[offset + 2] + '-' + array[offset + 3]); + offset += 4; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + + case 43:// 昨天PM2.5大气溶度 + for (int i = 0; i < 96; i++) { + // dataStrings[0] = + // String.valueOf(Integer.valueOf(array[offset + 0]+ + // array[offset + 1], + // 16)); + dataStrings[0] = Integer.toString(Integer.parseInt(array[offset + 0] + array[offset + 1], 16)); + offset += 2; + wCurvedatasByLamp(adomain, pn1, fn, dataStrings, td_ctime, batchtime, i);// 写曲线表 + td_ctime = Common.timeadd(td_ctime, 15); + } + break; + default: + break; + + }// while (data.length()>4) + + Protocol.deltempmeters(taskidString); + } + } + + /** + * 获取命令码 + * + * @param taskidString + * 任务号 + * @return + */ + private static String getCodeByTempmeter(String taskidString) { + String resultString = ""; + String strsql = "select code from tempmeters where id=" + taskidString; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return ""; + } + try { + rSet.next(); + resultString = rSet.getString("code"); + } catch (Exception e) { + // e.printStackTrace(); + Log.writelog(GW3761.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "-> tempmeters id:" + strsql); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + return resultString; + + } + + /** + * 更新抄表命令 + * + * @param taskidString + * 任务号 + * @param codeString + * 命令码 + */ + private void UpdateCodeByTempmeter(String taskidString, String codeString) { + // String resultString = ""; + String strsql = "update tempmeters set code ='" + codeString + "' where id=" + taskidString; + SQLHelper.ExecSql(strsql); + } + + /** 处理冻结类数据 电能表 */ + public void FreezeData(String data, String adomain, int pn, int fn, String taskidString) { + String codeString = getCodeByTempmeter(taskidString); + String field1 = "", field2 = "", field3 = "", field4 = "", field5 = "", fieldtime = ""; + switch (fn) { + case 161:// 日冻结正向有功电能示值(总、费率1~M) + field1 = "foract"; + field2 = "fa1"; + field3 = "fa2"; + field4 = "fa3"; + field5 = "fa4"; + fieldtime = "foracttime"; + break; + case 162:// 日冻结正向无功(组合无功1)电能示值(总、费率1~M) + field1 = "revact"; + field2 = "ra1"; + field3 = "ra2"; + field4 = "ra3"; + field5 = "ra4"; + fieldtime = "revacttime"; + break; + case 163:// 日冻结反向有功电能示值(总、费率1~M) + field1 = "forreact"; + field2 = "fr1"; + field3 = "fr2"; + field4 = "fr3"; + field5 = "fr4"; + fieldtime = "forreacttime"; + break; + case 164:// 日冻结反向无功(组合无功1)电能示值(总、费率1~M) + field1 = "revreact"; + field2 = "rr1"; + field3 = "rr2"; + field4 = "rr3"; + field5 = "rr4"; + fieldtime = "revreacttime"; + break; + } + + String td_d = "", rtime = ""; + String[] value = new String[5]; + String[] array; + array = data.split("-"); + int succeedCount = 0; + String meterCodeString = ""; + // ArrayList codeList = new ArrayList(); + try { + int offset = 0; + while (offset < array.length) { + int pn1 = getPnOrFn(array[offset], array[offset + 1], 0);// 信息点标识Pn + meterCodeString = array[offset] + array[offset + 1]; + offset += 2; + // int fn1 = getPnOrFn(array[offset], array[offset + 1],1);// + // 信息类标识Fn + meterCodeString = meterCodeString + array[offset] + array[offset + 1]; + offset += 2; + td_d = array[offset] + array[offset + 1] + array[offset + 2];// 日冻结类数据时标(3字节) + // 日月年 + offset += 3; + meterCodeString += td_d; + + rtime = "20" + array[offset + 4] + "-" + array[offset + 3] + "-" + array[offset + 2] + " " + + array[offset + 1] + ":" + array[offset + 0] + ":00"; + + offset += 5; + // rtime = Common.formattime2(rtime); + + int rates = Integer.parseInt(array[offset]);// 费率数 + offset++; + if (fn == 161 || fn == 163) { + for (int i = 0; i < rates + 1; i++) { + value[i] = GeneralString.formatA14(array[offset] + "-" + array[offset + 1] + "-" + + array[offset + 2] + "-" + array[offset + 3] + "-" + array[offset + 4]); + offset += 5; + } + // data = data.substring(start); + } else if (fn == 162 || fn == 164) { + for (int i = 0; i < rates + 1; i++) { + value[i] = GeneralString.formatA11(array[offset] + "-" + array[offset + 1] + "-" + + array[offset + 2] + "-" + array[offset + 3]); + offset += 4; + } + // data = data.substring(start); + } + + if (!value[0].equals("")) { // 抄表成功 + wMeterdaydatas(adomain, rates, pn1, fieldtime, rtime, field1, field2, field3, field4, field5, + value[0], value[1], value[2], value[3], value[4]); + codeString = codeString.replace(meterCodeString, ""); + succeedCount++; + + } + } // while (data.length()>4) + + if (codeString.equals("")) + Protocol.deltempmeters(taskidString);// 删除补抄表记录 + else if (succeedCount > 0) // 部分成功 + { + UpdateCodeByTempmeter(taskidString, codeString); + } + } catch (Exception e) { + Log.writelog(GW3761.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** 处理冻结类数据 电能表 */ + + public void FreezeDataF70(String data, String adomain, int pn, int fn, String batchtime, String taskidString) { + String codeString = getCodeByTempmeter(taskidString); + String field1 = "", field2 = "", field3 = "", field4 = "", field5 = "", fieldtime = ""; + switch (fn) { + case 70:// 日冻结正向有功电能示值(总、费率1~M) + field1 = "foract"; + field2 = "fa1"; + field3 = "fa2"; + field4 = "fa3"; + field5 = "fa4"; + fieldtime = "foracttime"; + break; + } + + String td_d = "", rtime = ""; + String[] value = new String[5]; + String[] array; + array = data.split("-"); + int succeedCount = 0; + int count = 0; + int num = 0; + String meterCodeString = ""; + // ArrayList codeList = new ArrayList(); + try { + int offset = 0; + while (offset < array.length) { + int pn1 = getPnOrFn(array[offset], array[offset + 1], 0);// 信息点标识Pn + meterCodeString = array[offset] + array[offset + 1]; + offset += 2; + // int fn1 = getPnOrFn(array[offset], array[offset + 1],1);// + // 信息类标识Fn + meterCodeString = meterCodeString + array[offset] + array[offset + 1]; + offset += 2; + td_d = array[offset] + array[offset + 1] + array[offset + 2];// 日冻结类数据时标(3字节) + // 日月年 + offset += 3; + meterCodeString += td_d; + + count = Integer.valueOf(array[offset]); + offset++; + + num = 0; + + for (int i = 0; i < count; i++) { + // 测量点 + pn1 = Integer.parseInt(array[offset + 1] + array[offset + 0], 16); + offset += 2; + // 抄读时间 + rtime = "20" + array[offset + 4] + "-" + array[offset + 3] + "-" + array[offset + 2] + " " + + array[offset + 1] + ":" + array[offset + 0] + ":00"; + offset += 5; + + // 正向有功总 + value[0] = GeneralString.formatA11(array[offset] + "-" + array[offset + 1] + "-" + array[offset + 2] + + "-" + array[offset + 3]); + offset += 4; + + if (!value[0].equals("")) { // 抄表成功 + wdaydatas(adomain, 1, pn1, fieldtime, rtime, field1, field2, field3, field4, field5, value[0], + value[1], value[2], value[3], value[4]); + } + } + + /* + * if (!value[0].equals("")) { // 抄表成功 wdaydatas(adomain, 1, + * pn1, fieldtime, rtime, field1, field2, field3, field4, + * field5, value[0], value[1], value[2], value[3], value[4]); + * codeString = codeString.replace(meterCodeString, ""); + * succeedCount++; } + */ + } // while (data.length()>4) + + Protocol.deltempmeters(taskidString);// 删除补抄表记录 + /* + * if (codeString.equals("")) + * Protocol.deltempmeters(taskidString);// 删除补抄表记录 else if + * (succeedCount > 0) // 部分成功 { UpdateCodeByTempmeter(taskidString, + * codeString); } + */ + } catch (Exception e) { + Log.writelog(GW3761.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->ERROR:" + e.getMessage()); + } + } + + /** + * 计算DA/DT + * + * @param flag + * 为0时计算信息点标识DA,为1计算信息类标识DT + */ + public static String GetDAOrDT(int value, int flag) { + int d = 0; + String D1, D2 = "0"; + + if (value == 0) { + D1 = "0"; + D2 = "0"; + } else { + d = value % 8; + + if (d == 0) { + D1 = "1" + repeat(7, '0'); + d = value / 8 - 1; + if (flag == 0) { + d = d + 1; + } + } else { + D1 = "1" + repeat(d - 1, '0'); + d = value / 8; + if (flag == 0) { + d = d + 1; + } + } + } + + D1 = Common.right("00" + Common.binarytohex(D1), 2); + D2 = Common.right("00" + Common.inttohex(d), 2); + return D1 + D2; + } + + /** 由信息类标识Fn获取曲线表中相应字段名 */ + /* 没有功率因数 0D 105 */ + public String getField(int fn) { + String field = ""; + switch (fn) { + case 81:// 测量点有功功率曲线 + field = "actpow"; + break; + case 85:// 测量点无功功率曲线 + field = "reactpow"; + break; + case 89:// 测量点A相电压曲线 + field = "avol"; + break; + case 90:// 测量点B相电压曲线 + field = "bvol"; + break; + case 91:// 测量点C相电压曲线 + field = "cvol"; + break; + case 92:// 测量点A相电流曲线 + field = "acur"; + break; + case 93:// 测量点B相电流曲线 + field = "bcur"; + break; + case 94:// 测量点C相电流曲线 + field = "ccur"; + break; + case 95:// 测量点零序电流曲线 + field = "zeroseqcur"; + break; + case 101:// 测量点正向有功总电能示值曲线 + field = "foract"; + break; + case 102:// 测量点正向无功总电能示值曲线 + field = "forreact"; + break; + case 103:// 测量点反向有功总电能示值曲线 + field = "revact"; + break; + case 104:// 测量点反向无功总电能示值曲线 + field = "revreact"; + break; + default: + Log.writelog(GW3761.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Fn:" + String.valueOf(fn)); + } + + return field; + } + + /** 返回指定字符的重复 */ + public static String repeat(int len, char c) { + StringBuffer sbf = new StringBuffer(); + int i = 0; + while (i < len) { + i += 1; + sbf.append(c); + } + return sbf.toString(); + } + + /** + * 根据376.1协议生成下行报文 + * + * @param cdomain + * 控制域 + * @param adomain + * 地址域 + * @param afn + * 应用功能码 + * @param seqdomain + * 帧序列域 + * @param pn + * 测量点 + * @param fn + * 功能码 + * @param params + * 参数 + */ + public String create3761(String cdomain, String adomain, String afn, String seqdomain, int pn, int fn, + String params) { + String cmd = "";// 报文数据 + + int bytes = 12 + params.length() / 2;// 字节长度(1+5+1+1+2+2+参数长度) + String binarylen = Common.inttobinary(bytes); + binarylen = binarylen + "10";// 加协议标识Q/GDW 376.1—2009 + String hexlen = Common.binarytohex(binarylen); + hexlen = Common.right("0000" + hexlen, 4); + char[] chr = hexlen.toCharArray(); + hexlen = String.valueOf(chr[2]) + String.valueOf(chr[3]) + String.valueOf(chr[0]) + String.valueOf(chr[1]); + + // 组织数据单位标识:信息点DA(DA1,DA2):Pn;信息类DT(DT1,DT2):Fn + String DA = GetDAOrDT(pn, 0); + String DT = GetDAOrDT(fn, 1); + + // 计算校验码 + long hextotal = 0; + cmd = cdomain + adomain + afn + seqdomain + DA + DT + params; + int i = 0; + while (i < cmd.length()) { + hextotal = hextotal + Long.parseLong(cmd.substring(i, i + 2), 16); + i = i + 2; + } + + // 校验码 + String cscode = Common.right(Long.toHexString(hextotal), 2); + cmd = "68" + hexlen + hexlen + "68" + cdomain + adomain + afn + seqdomain + DA + DT + params + cscode + "16"; + cmd = Common.str2split(cmd).toUpperCase(); + + return cmd.substring(0, cmd.length() - 1); + } + + public String create3761(String cdomain, String adomain, String afn, String seqdomain, String params) { + String cmd;// 报文数据 + + int bytes = 8 + params.length() / 2;// 字节长度(1+5+1+1+参数长度) + String binarylen = Common.inttobinary(bytes); + binarylen = binarylen + "10";// 加协议标识Q/GDW 376.1—2009 + String hexlen = Common.binarytohex(binarylen); + hexlen = Common.right("0000" + hexlen, 4); + char[] chr = hexlen.toCharArray(); + hexlen = String.valueOf(chr[2]) + String.valueOf(chr[3]) + String.valueOf(chr[0]) + String.valueOf(chr[1]); + + // 计算校验码 + long hextotal = 0; + cmd = cdomain + adomain + afn + seqdomain + params; + int i = 0; + while (i < cmd.length()) { + hextotal = hextotal + Long.parseLong(cmd.substring(i, i + 2), 16); + i = i + 2; + } + + // 校验码 + String cscode = Common.right(Long.toHexString(hextotal), 2); + cmd = "68" + hexlen + hexlen + "68" + cdomain + adomain + afn + seqdomain + params + cscode + "16"; + cmd = Common.str2split(cmd).toUpperCase(); + return cmd.substring(0, cmd.length() - 1); + } + + /** + * 解析上行报文数据 + * + * @param cmdid + * @param datas + * 完整报文 + * @param state + * GPRS通信响应状态 + * @param taskidString + * 定采任务号 + */ + public void dataAnalysis(int cmdid, String datas, int state, String batchtime, String taskidString) { + + String[] array = datas.split("-"); + String cdomain = array[6];// 控制域 + String acd = Common.hextobinary(cdomain).substring(2, 3);// 要求访问位ACD.ACD=1表示终端有重要事件等待访问 + String terminal = array[8] + array[7] + array[10] + array[9];// 终端地址 + + if (cmdid != 0) {// 页面指令响应数据,写入结果表 + wReceiveData(cmdid, terminal, cmdcode, state); + return; + } + try { + + String AFN = array[12];// 应用层功能码(AFN) + int pn = getPnOrFn(array[14], array[15], 0);// 信息点标识Pn + int fn = getPnOrFn(array[16], array[17], 1);// 信息类标识Fn + + if (AFN.equals("00")) { // "确认/否认"; + if (!taskidString.equals("")) + Protocol.deltempmeters(taskidString); + return; + } + + String data = ""; + if (acd.equals("1")) { + data = datas.substring(42, datas.length() - 12); + } else { + data = datas.substring(42, datas.length() - 6); + } + // array = data.split("-"); + // + + if (AFN.equals("AC")) { + + switch (fn) { + case 6:// 灯控器巡测数据-主动上报 + FreezeDataF6(data, terminal, pn, fn, batchtime, taskidString); + break; + case 7:// 灯控器巡测数据-主站查询 + FreezeDataF7(data, terminal, pn, fn, batchtime, taskidString); + break; + // case 41: // 昨日正向有功电能量 + // FreezeDataF41(data, terminal, pn, fn, batchtime, + // taskidString); + // break; + case 51: // 主控开关小时冻结交采数据 + FreezeDataF51(data, terminal, pn, fn, batchtime, taskidString); + break; + + default: + CurveDataLamp(data, terminal, pn, fn, batchtime, taskidString); + break; + } + + } + if (AFN.equals("AD")) { + switch (fn) { + case 60:// F60:回路状态曲线 + CurveData(data, terminal, pn, fn, batchtime, taskidString); + break; + case 70:// F70:单灯电能日冻结数据 + FreezeDataF70(data, terminal, pn, fn, batchtime, taskidString); + break; + + } + } + + } catch (Exception e) { + e.printStackTrace(); +// if (Work.language.equals("en")) +// wabnormal(terminal, datas, "Concentrator uplink packet application does not comply with the rules!", +// "Auto Server", Common.getDateStr0()); +// else +// wabnormal(terminal, datas, "集中器上行报文不符合应用规则!", "前置机", Common.getDateStr0()); + } + } + + /** + * 解析串口接收的数据 + * + * @param cmdid + * 指令数据ID + * @param receivedata + * 响应数据 + */ + public void dataExecute(int cmdid, String receivedata, int state, String batchtime, String taskidString) { + cmdcode += receivedata; + + // 检验数据报文 + if (!cmdcode.startsWith("68")) { + int count = cmdcode.indexOf("68"); + if (count == -1) { + cmdcode = ""; + } else { + cmdcode = cmdcode.substring(count); + } + } else if (cmdcode.startsWith("68")) { + int count = cmdcode.lastIndexOf("16-"); + if (count > 0) { + String time = Common.getDateStr0(); + + String tempcode = cmdcode.substring(0, count + 2); + Log.writelog(clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->Com response data:" + tempcode); + + String[] array = tempcode.split("-"); + int arraylen = array.length; + String terminal = array[8] + array[7] + array[10] + array[9];// 终端地址 + if (arraylen < 20) { + if (Work.language.equals("en")) + wabnormal(terminal, cmdcode, " packet length less than 20 bytes!", // 报文长度不足20字节 + "Event data parsing", time);// 事件数据解析 + else + wabnormal(terminal, cmdcode, "报文长度不足20字节!", // 报文长度不足20字节 + "事件数据解析", time);// 事件数据解析 + return; + } + String hexlen1 = array[1] + array[2]; + String hexlen2 = array[3] + array[4]; + if (hexlen1.equals(hexlen2)) { + Long lngParity = (long) 0; + for (int i = 6; i < arraylen - 2; i++) { + lngParity += Long.parseLong(array[i], 16); + } + String hexParity = Long.toHexString(lngParity).toUpperCase(); + if (hexParity.length() > 2) { + hexParity = Common.right(hexParity, 2); + } else { + hexParity = Common.right("00" + hexParity, 2); + } + if (hexParity.equals(array[arraylen - 2])) { + dataAnalysis(cmdid, tempcode, state, batchtime, taskidString); + } else { + if (Work.language.equals("en")) + wabnormal(terminal, cmdcode, "CS Error!", // 集中器上行报报文长度校验码不正确 + "Event data parsing", time);// 事件数据解析 + else + wabnormal(terminal, cmdcode, "集中器上行报报文长度校验码不正确!", // 集中器上行报报文长度校验码不正确 + "事件数据解析", time);// 事件数据解析 + } + } + cmdcode = cmdcode.substring(count + 3); + } + } + } + + /** + * 事件数据写入事件表(EventData) + * + * @param datas + * 完整报文 + * @param terminal + * 终端地址 + */ + public void EventData(String terminal, String datas) { + wEventData(terminal, "5", datas, "0002");// 写入事件表(EventData) + } + + /** 由上行报文数据解析数据,flag为0时为Pn,1时为Fn */ + public int getPnOrFn(String hex1, String hex2, int flag) { + int i = Integer.parseInt(hex1, 16); + String binary = Integer.toBinaryString(i); + int mod = binary.length(); + i = Integer.parseInt(hex2, 16); + if (flag == 0) { + if (i > 0) { + i -= 1; + } + } + return i * 8 + mod; + } + + /** + * 响应数据解析处理 + * + * @param cmdid + * 转发的指令ID(定采的指令ID为0) + * @param terminal + * 终端地址 + * @param cmdcode + * 上行报文数据 + * @param state + * 抄读状态(0为正常抄读,1为不在线,2为忙,3为超时,4为GPRS服务器连接失败) + * @param afncode + * @param comtype + * 通信类型(0001为串口,0002为GPRS) + * @param Fn + * 命令的功能码(路灯系统) + * @param taskidString + * 定采任务号 + * @param outdata + * 发设置命令 + */ + public void ResolvingData(int cmdid, String terminal, String cmdcode, int state, String comtype, String afncode, + int Fn, String batchtime, String taskidString, String outdata) { + if (comtype.equals("0001")) { // 串口数据解析 + if (cmdid > 0) { // 页面命令 + wReceiveData(cmdid, terminal, cmdcode, state); + } else { + if (cmdcode.length() == 0) {// 抄读不成功 + // 2015 07 16 wwb 补抄数据 + if (Fn == 7) + complementary_data(terminal, outdata, batchtime); + } else { + // 需要对报文进行校验 + dataExecute(cmdid, cmdcode, state, batchtime, taskidString); + } + } + } else if (comtype.equals("0002")) {// GPRS 数据解析 + if (cmdid > 0) {// 页面指令响应数据,写入结果表 + wReceiveData(cmdid, terminal, cmdcode, state); + } else {// 定采指令响应数据解析 + if (state == 0) { + dataAnalysis(cmdid, cmdcode, state, batchtime, taskidString); + } else { + if (Fn == 7) // 2015 07 16 wwb 补抄数据 + complementary_data(terminal, outdata, batchtime); + } + } + } + } + + /** 事件表(EventData)数据解析处理,解析后写入事件信息表(EventInfo) */ + public void AnalyzerData(int eventid, String time, String datas) { + + int eventcount = 0;// 事件记录数 + int bugcount = 0;// 故障记录数 + String times = "";// 故障发生时间 + String ccomid1 = "";// 灯地址 + String barcode1 = ""; + String barcode2 = ""; + String bugstatus = "";// 灯故障状态字 + + String[] array = datas.split(" "); + System.out.println(datas); + String cdomain = array[6];// 控制域 + String acd = Common.hextobinary(cdomain).substring(2, 3);// 要求访问位ACD.ACD=1表示终端有重要事件等待访问 + String terminal = array[8] + array[7] + array[10] + array[9];// 终端地址 + String terminalNameString = BusinessParameter.getgname(terminal);// 获取集中器名称 + // Log.writelog(GW3761.clazzName, "AnalyzerData->start "+datas); + try { + + String data; + if (acd.equals("1")) { + data = datas.substring(54, datas.length() - 12); + } else { + data = datas.substring(54, datas.length() - 6); + } + array = data.split(" "); + + String ec1 = array[0];// 当前重要事件计数器ec1 + String ec2 = array[1];// 当前重要事件计数器ec2 + int intpm = Integer.parseInt(array[2], 16); + int intpn = Integer.parseInt(array[3], 16); + if (intpm < intpn) { + eventcount = intpn - intpm; + } else { + eventcount = 256 + intpn - intpm; + } + int type = 0;// 故障上报类型:1.灯具故障 2.回路设备故障 3.集中器故障 4.传感器故障 5.配电箱异常故障 + int i = 0; + int offset; + int num = 0; + int count = 0; + int gcomid;// 组号 + String smsinfo; + String ginfo; + String remark; + String smsContent; + int typeErr = 0; + + while (i < array.length) { + smsinfo = ""; + smsContent = ""; + ccomid1 = ""; + barcode1 = ""; + gcomid = 0; + ginfo = ""; + offset = i; + int erclen = Common.hextoint(array[offset + 1]); + int erccode = Common.hextoint(array[offset]); + offset += 2; + // 发生时间 + times = GeneralString.formatA15(array[offset + 0] + "-" + array[offset + 1] + "-" + array[offset + 2] + + "-" + array[offset + 3] + "-" + array[offset + 4]); + offset += 5; + int error = 0; + // Log.writelog(GW3761.clazzName, "AnalyzerData->start + // "+erccode); + + // String content = ""; + // String encontent = ""; + // String syscodeSql = "SELECT type, code, content, remark, + // recordid, encontent, rucontent FROM syscode WHERE code = '" + + // erccode + "'"; + // ResultSet syscodeSet = + // SQLHelper.ExecProcwCommands(syscodeSql); + // if (syscodeSet == null) { + // return; + // } + // while (syscodeSet.next()) { + // content = syscodeSet.getString("content"); + // encontent = syscodeSet.getString("encontent"); + // } + + switch (erccode) { + case 43:// 灯控器故障预警事件记录 43 type 1-16 + { + num = Common.hextoint(array[offset + 1] + array[offset + 0]);// 灯装置序号 + offset += 2; + ccomid1 = BusinessParameter.getCcomid(terminal, num);// 灯地址 + barcode1 = BusinessParameter.getbarcode(ccomid1);// 测量点号 + gcomid = BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 + ginfo = BusinessParameter.getgname(terminal, gcomid);// 集中器名称 + if (Work.language.equals("en")) + // smsinfo = terminal + "集中器下的组 " + ginfo + " + // 发生预警,故障内容为:"; + smsinfo = "The group " + ginfo + " under the concentrator " + terminalNameString + "[" + + terminal + "] failed for the reason of "; + else + smsinfo = terminalNameString + "[" + terminal + "]集中器下的 " + ginfo + " 组发生预警,故障内容为:"; + num = Integer.parseInt(array[offset], 16);// 故障字 + offset++; + + // 灯杆倾斜 + if ((num & 0x01) > 0) // 灯杆倾斜 + { + typeErr = 7; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x04) > 0) // 温度预警 + { + typeErr = 1; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x08) > 0) // 漏预警 + { + typeErr = 2; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x10) > 0) // 相位不符预警 + { + typeErr = 3; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x20) > 0) // 线路不符警示 + { + typeErr = 4; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x40) > 0) // 台区不符警示 + { + typeErr = 5; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x80) > 0) // 使用寿命到期预警 + { + typeErr = 6; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + // 预警故障状态字2 + // num = Integer.parseInt(array[offset], 16); + offset++; + + } + break; + case 44:// 灯控器故障报警事件记录 44 type 21-40 + { + num = Common.hextoint(array[offset + 1] + array[offset + 0]);// 灯装置序号 + offset += 2; + // Log.writelog(GW3761.clazzName, + // "AnalyzerData->getinfostart "+erccode); + ccomid1 = BusinessParameter.getCcomid(terminal, num);// 灯地址 + barcode1 = BusinessParameter.getbarcode(ccomid1); + gcomid = BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 + ginfo = BusinessParameter.getgname(terminal, gcomid); + // Log.writelog(GW3761.clazzName, "AnalyzerData->getinfoover + // "+erccode); + if (Work.language.equals("en")) + // smsinfo = terminal + "集中器下的组" + ginfo + + // "发生故障,故障内容为:"; + smsinfo = "The group " + ginfo + " under the concentrator " + terminalNameString + "[" + + terminal + "] failed for the reason of "; + else + smsinfo = terminalNameString + "[" + terminal + "]集中器下的" + ginfo + "组发生故障,故障内容为:"; + num = Integer.parseInt(array[offset], 16); + offset++; + // Log.writelog(GW3761.clazzName, "AnalyzerData->analtzernum + // "+num); + // 20161211 有光源故障和电源故障时不显示灯具故障 + if (((num & 0x80) > 0) || ((num & 0x40) > 0)) { + num = num & 0xFE; + } + + if ((num & 0x01) > 0) // 灯具故障 + { + typeErr = 21; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x02) > 0) // 温度故障 + { + typeErr = 22; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x04) > 0) // 超负荷报警 + { +// typeErr = 23; + typeErr = 22; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x08) > 0) // 功率因数过低 + { + typeErr = 24; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x40) > 0) // 灯珠故障 + { + typeErr = 26; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x80) > 0) // 电源故障 + { +// typeErr = 27; + typeErr = 23; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x10) > 0) // 时钟故障 + { + typeErr = 25; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + // num = Integer.parseInt(array[offset], 16); + offset++; + } + break; + case 45:// 主控故障预警事件记录 45 type 41-60 + { + num = Common.hextoint(array[offset + 1] + array[offset + 0]);// 灯装置序号 + offset += 2; + ccomid1 = BusinessParameter.getMcomid(terminal, num);// 主控地址 + // ccomid1 = String.valueOf(num); + barcode1 = BusinessParameter.getMbarcode(terminal, ccomid1); + if (Work.language.equals("en")) + smsinfo = "The line control " + ccomid1 + " under the concentrator " + terminalNameString + "[" + + terminal + "] failed for the reason of "; + else + smsinfo = terminalNameString + "[" + terminal + "]集中器下 " + ccomid1 + " 主控发生报警,预警内容为:"; + + num = Integer.parseInt(array[offset], 16); + if ((num & 0x01) > 0) // A相电流过流 + { + typeErr = 41; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x02) > 0) // B相电流过流 + { + typeErr = 41; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x04) > 0) // C相电流过流 + { + typeErr = 42; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x08) > 0) // A相断路 + { + typeErr = 44; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x10) > 0) // B相断路 + { + typeErr = 45; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x20) > 0) // C相断路 + { + typeErr = 46; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + if ((num & 0x80) > 0) { + typeErr = 43; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + offset += 2; + } + break; + case 46:// 主控故障报警事件记录 46 type 61-80 + { + int ErrCount = 0; + num = Common.hextoint(array[offset + 1] + array[offset + 0]);// 主控开关地址 + offset += 2; + ccomid1 = BusinessParameter.getMcomid(terminal, num);// 主控地址 + // ccomid1 = String.valueOf(num); + barcode1 = BusinessParameter.getMbarcode(terminal, ccomid1); + if (Work.language.equals("en")) + // smsinfo = terminal + "集中器下" + ccomid1 + + // "主控发生报警,预警内容为:"; + smsinfo = "The line control " + ccomid1 + " under the concentrator " + terminalNameString + "[" + + terminal + "] failed for the reason of "; + else + smsinfo = terminalNameString + "[" + terminal + "]集中器下 " + ccomid1 + " 主控发生报警,预警内容为:"; + num = Integer.parseInt(array[offset], 16); + offset++; + + if ((num & 0x01) > 0) // A相电压超限 + { +// typeErr = 61; + typeErr = 73; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x02) > 0) // B相电压超限 + { +// typeErr = 62; + typeErr = 76; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x04) > 0) // C相电压超限 + { +// typeErr = 63; + typeErr = 75; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x08) > 0) // A相过载故障 + { +// typeErr = 64; + typeErr = 74; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x10) > 0) // A相 欠载故障 + { + typeErr = 65; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + ErrCount++; + } + + if ((num & 0x20) > 0) // B相过载故障 + { + typeErr = 66; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x40) > 0) // B相过载故障 + { + typeErr = 67; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + ErrCount++; + } + + if ((num & 0x80) > 0) // C相过载故障 + { + typeErr = 68; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + num = Integer.parseInt(array[offset], 16); + offset++; + + if ((num & 0x01) > 0) // C相过载故障 + { + typeErr = 69; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + ErrCount++; + } + + if (ErrCount > 0) { // 更新主控开关的欠载的状态 2017 11 04 + // underload + UpdateMControlUnderloadState(terminal, ccomid1, '1'); + } else { + UpdateMControlUnderloadState(terminal, ccomid1, '0'); + } + + if ((num & 0x02) > 0) // A相 功率因数过低 + { + typeErr = 70; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x04) > 0) // B相 功率因数过低 + { + typeErr = 71; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x08) > 0) // C相 功率因数过低 + { + typeErr = 72; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x80) > 0) // 交流接触器故障 + { + typeErr = 73; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + } + break; + case 47:// 配电箱状态记录 47 type 81-100 + { + ccomid1 = Integer.toString(Integer.parseInt(array[offset + 0] + array[offset + 1], 16)); + offset += 2; + if (Work.language.equals("en")) { + // smsinfo = terminal + "集中器下发生事件,事件内容为:"; + smsinfo = "A event occurred under the concentrator " + terminalNameString + "[" + terminal + + "] ,and the event was that "; + } else { + smsinfo = terminalNameString + "[" + terminal + "]集中器下发生事件,事件内容为:"; + } + + num = Integer.parseInt(array[offset], 16); + offset++; + + if ((num & 0x01) > 0) // 配电箱前门开启 + { + typeErr = 81; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x02) > 0) // 配电箱后面开启 + { + typeErr = 82; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + num = Integer.parseInt(array[offset], 16); + offset++; + } + break; + case 48:// 传感器事件记录 48 101-120 + { + // ccomid1 = Integer.toString(Integer.parseInt(array[offset + // + 0] + array[offset + 1], + // 16)); + offset += 2; + if (Work.language.equals("en")) { + smsinfo = "M2.5 sensor event occurred under the concentrator " + terminalNameString + "[" + + terminal + "] ,and the event was that "; + } else { + smsinfo = terminalNameString + "[" + terminal + "]集中器的PM2.5传感器发生事件,事件内容为:"; + } + + num = Integer.parseInt(array[offset], 16); + offset++; + + if ((num & 0x01) > 0) // PM2.5通信异常故障 + { + typeErr = 101; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + offset++; + } + break; + case 49:// 灯具终端离线报警49 + { // 数量 + // num = Integer.parseInt(array[offset + 1] + array[offset], + // 16); + count = Common.hextoint(array[offset + 1] + array[offset + 0]);// 灯装置序号 + offset += 2; + + typeErr = 44; + for (i = 0; i < count; i++) { + num = Common.hextoint(array[offset + 1] + array[offset + 0]); + ccomid1 = BusinessParameter.getCcomid(terminal, num);// 灯地址 + barcode1 = BusinessParameter.getbarcode(ccomid1); + gcomid = BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 + ginfo = BusinessParameter.getgname(terminal, gcomid); + if (Work.language.equals("en")) + // smsinfo = terminal + "集中器下的组" + ginfo + + // "发生故障,故障内容为:"; + { + smsinfo = "The group " + ginfo + " under the concentrator " + terminalNameString + "[" + + terminal + "] Communication failure occurred! "; + remark = "lamp device failure"; + } else { + smsinfo = terminalNameString + "[" + terminal + "]集中器下的 " + ginfo + " 组,发生灯具掉线!"; + remark = "通迅异常"; + } + updateConOnline(ccomid1, 0);/* 更新为离线状态=0离线 =1在线 */ + // InsertEventInfo(time, terminal, gcomid, ccomid1, "", + // typeErr, remark, barcode1, "", + // eventid); + /* 更新设备状态信息离线 */ + + offset += 2; + /* 事件推送到第三方、短信、微信、邮件 */ + // if (BusinessParameter.IsSend(terminal, typeErr)) + smsContent = smsinfo + "[" + String.valueOf(count) + " PCS]"; + /* + * if(smsContent.length()==0) smsContent = smsinfo + + * String.valueOf(Integer.valueOf(ccomid1)); else + * smsContent = smsContent + "," + + * String.valueOf(Integer.valueOf(ccomid1)); + */ + } + } + break; + /* + * case 50:// 回路状态变化事件err50 { num = Common.hextoint(array[offset + * + 1] + array[offset + 0]);// 主控开关地址 offset += 2; ccomid1 = + * BusinessParameter.getMcomid(terminal, num); barcode1 = + * BusinessParameter.getMbarcode(terminal, ccomid1); + * + * num = Integer.parseInt(array[offset], 16); offset++; int + * realyrunmode = 0;// 回路运行方式 int schedulerunmode = 0;// + * 回路自动运行模式 int realy1sta = 0;// 回路继电器状态 int ACcontactor1sta = + * 0;// 回路交流接触器状态 int timing = 0;// 请求校时 + * + * if ((num & 0x01) > 0) realyrunmode = 1; + * + * if ((num & 0x02) > 0) schedulerunmode = 1; + * + * if ((num & 0x04) > 0) realy1sta = 1; + * + * num = Integer.parseInt(array[offset], 16); offset++; + * + * if ((num & 0x01) > 0) ACcontactor1sta = 1; + * + * if ((num & 0x02) > 0) timing = 1; wmControlEvent(barcode1, + * ccomid1, terminal, time, realyrunmode, schedulerunmode, + * realy1sta, ACcontactor1sta, timing, 50, eventid); // 状态变化 + * }break; + */ + + case 51:// 配电箱供电异常事件记录 + { + // 集中器 + // ccomid1 = Integer.toString(Integer.parseInt(array[offset + // + 0] + array[offset + 1], + // 16)); + offset += 2; + // 配电箱供电异常状态字1 + num = Integer.parseInt(array[offset], 16); + offset++; + if ((num & 0x01) > 0) // 负荷突增 + { + typeErr = 121; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + if ((num & 0x02) > 0) // 线路缺相 + { + typeErr = 122; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + + // 配电箱供电异常状态字2 + offset++; + } + break; + + case 52:// 灯具状态变化上报 + { + count = Common.hextoint(array[offset + 1] + array[offset + 0]); + offset += 2; + for (int j = 0; j < count; j++) { + // 灯装置序号1 + num = Common.hextoint(array[offset + 1] + array[offset + 0]); + ccomid1 = BusinessParameter.getCcomid(terminal, num);// 灯地址 + barcode1 = BusinessParameter.getbarcode(ccomid1); + gcomid = BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 + ginfo = BusinessParameter.getgname(terminal, gcomid); + offset += 2; + + // 灯具状态字1 + num = Integer.parseInt(array[offset], 16); + offset++; + // 更新灯具开关灯状态字 + UpdateLampOnState(terminal, ccomid1, (num & 0x20)); + // 更新灯具手自动状态字 + UpdateLampHandState(terminal, ccomid1, (num & 0x04)); + /* + * if ((num & 0x40) > 0) // 意外关灯 { typeErr = 26; if + * (Work.language.equals("en")) remark = + * "Accidentally turn off the lights"; else remark = + * "意外关灯"; if (BusinessParameter.IsSend(terminal, + * typeErr)) if (smsContent.length() == 0) smsContent = + * smsinfo + remark; else smsContent = smsContent + ";" + * + remark; + * + * InsertEventInfo(time, terminal, gcomid, ccomid1, "", + * typeErr, remark, barcode1, "", eventid); } if ((num & + * 0x80) > 0) // 意外开灯 { typeErr = 27; if + * (Work.language.equals("en")) remark = + * "Accidentally turn on the light"; else remark = + * "意外开灯"; if (BusinessParameter.IsSend(terminal, + * typeErr)) if (smsContent.length() == 0) smsContent = + * smsinfo + remark; else smsContent = smsContent + ";" + * + remark; + * + * InsertEventInfo(time, terminal, gcomid, ccomid1, "", + * typeErr, remark, barcode1, "", eventid); } + */ + // 灯具状态字1 + offset++; + } + } + break; + + case 53: // 集中器和灯控器通讯恢复事件 + { + count = Common.hextoint(array[offset + 1] + array[offset + 0]); + offset += 2; + for (int j = 0; j < count; j++) { + // 灯装置序号1 + num = Common.hextoint(array[offset + 1] + array[offset + 0]); + ccomid1 = BusinessParameter.getCcomid(terminal, num);// 灯地址 + barcode1 = BusinessParameter.getbarcode(ccomid1); + gcomid = BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 + ginfo = BusinessParameter.getgname(terminal, gcomid); + offset += 2; + +// typeErr = 28; +// if (Work.language.equals("en")) +// remark = "Lamp controller communication recovery"; +// else +// remark = "灯控器通讯恢复"; + updateConOnline(ccomid1, 1);/* 更新为离线状态=0离线 =1在线 */ + // InsertEventInfo(time, terminal, 0, ccomid1, "", + // typeErr, remark, barcode1, "", eventid); + } + } + break; + case 54: // 线路被盗事件上报 + { + num = Common.hextoint(array[offset + 0]); + int num1 = Common.hextoint(array[offset + 1]); + int num2 = Common.hextoint(array[offset + 2]); + offset += 4; + typeErr = 141; + buildEventInfo(eventid, time, ccomid1, barcode1, terminal, gcomid, smsContent, typeErr); + } + break; + /* + * case 55: // 线路供电异常事件 { count = Common.hextoint(array[offset + + * 1] + array[offset + 0]); offset += 2; for (int j = 0; j < + * count; j++) { // 灯装置序号1 num = Common.hextoint(array[offset + + * 1] + array[offset + 0]); ccomid1 = + * BusinessParameter.getCcomid(terminal, num);// 灯地址 barcode1 = + * BusinessParameter.getbarcode(ccomid1); gcomid = + * BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 ginfo = + * BusinessParameter.getgname(terminal, gcomid); offset += 2; + * + * typeErr = 28; if (Work.language.equals("en")) remark = + * "Lamp controller communication recovery"; else remark = + * "灯控器通讯恢复"; + * + * InsertEventInfo(time, terminal, 0, ccomid1, "", typeErr, + * remark, barcode1, "", eventid); } }break; + * + * case 56: // 线路供电异常事件 { count = Common.hextoint(array[offset + + * 1] + array[offset + 0]); offset += 2; for (int j = 0; j < + * count; j++) { // 灯装置序号1 num = Common.hextoint(array[offset + + * 1] + array[offset + 0]); ccomid1 = + * BusinessParameter.getCcomid(terminal, num);// 灯地址 barcode1 = + * BusinessParameter.getbarcode(ccomid1); gcomid = + * BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 ginfo = + * BusinessParameter.getgname(terminal, gcomid); offset += 2; + * + * typeErr = 28; if (Work.language.equals("en")) remark = + * "Lamp controller communication recovery"; else remark = + * "灯控器通讯恢复"; + * + * InsertEventInfo(time, terminal, 0, ccomid1, "", typeErr, + * remark, barcode1, "", eventid); } }break; + */ + + default: + break; + } + // + // if (BusinessParameter.IsSend(terminal, typeErr)) + // if (!smsContent.equals("")) {// 加发送短信息处理 + // // smsinfo = smsinfo + smsContent; + // smsContent = smsContent + "."; + // SendSMS(terminal, smsContent.trim()); + // SendMail(terminal, smsContent.trim()); + // SendWachat(terminal, smsContent.trim()); + // } + + /* + * if (erccode == 43) {// 灯控器故障预警事件记录 int count = + * Common.hextoint(array[i + 7]);// 故障数量 for (int j = 0; j < + * count; j++) { // int num = Common.hextoint(array[j * 6 + i + + * 9] + array[j * 6 + i + 8]);// 灯装置序号 // ccomid1 = + * BusinessParameter.getCcomid(terminal, num);// 灯地址 // barcode1 + * = BusinessParameter.getbarcode(ccomid1); int gcomid = + * BusinessParameter.getgcomid(terminal, ccomid1);// 组地址 String + * state1 = array[j * 6 + i + 12];// 故障状态字1 state1 = + * Common.right("00000000" + Common.hextobinary(state1), 8); + * String state2 = array[j * 6 + i + 13];// 故障状态字2 state2 = + * Common.right("00000000" + Common.hextobinary(state2), 8); if + * (ccomid1.length() == 0) { wabnormal(terminal, datas, + * "集中器上行报文不符合应用(不存在故障灯)!", "前置机", time); } else { + * wEventInfoNew(state1, state2, time, terminal, gcomid, + * ccomid1, "", barcode1, barcode2); } } } else if (erccode == + * 43 || erccode == 42) { // 主控状态变化事件数据解析 int count = + * Common.hextoint(array[i + 7]);// 故障数量 for (int j = 0; j < + * count; j++) { int num = Common.hextoint(array[j * 6 + i + 8] + * + array[j * 6 + i + 9]);// 主控装置序号 ccomid1 = + * BusinessParameter.getCcomid(terminal, num);// 主控地址 String + * state1 = array[j * 6 + i + 10];// 运行状态字1 state1 = + * Common.right("00000000" + Common.hextobinary(state1), 8); + * String state2 = array[j * 6 + i + 11];// 运行状态字2 state2 = + * Common.right("00000000" + Common.hextobinary(state2), 8); + * String state3 = array[j * 6 + i + 12];// 故障状态字1 state3 = + * Common.right("00000000" + Common.hextobinary(state3), 8); + * String state4 = array[j * 6 + i + 13];// 故障状态字2 state4 = + * Common.right("00000000" + Common.hextobinary(state4), 8); + * + * // 主控状态变化事件状态解析 if (ccomid1.length() == 0) { + * wabnormal(terminal, datas, "集中器上行报文不符合应用(不存在故障主控开关)!", "前置机", + * time); } else { mControlEvent(state1, state2, state3, state4, + * time, terminal, ccomid1, erccode); } } } + */ + i += erclen + 2; + } + } catch (Exception e) { + // 写入异常报文数据表 + if (Work.language.equals("en")) { + Protocol.wabnormal(terminal, datas, + "Concentrator uplink packet application does not comply with the rules!", "Auto Server", + Common.getDateStr0()); + } else { + Protocol.wabnormal(terminal, datas, "集中器上行报文不符合应用规则!", "前置机", time); + } + } + } + + public String buildEventInfo(int eventid, String time, String ccomid1, String barcode1, String terminal, int gcomid, + String smsContent, int typeErr) { + + String content = ""; + String encontent = ""; + String syscodeSql = "SELECT type, code, content, remark, recordid, encontent, rucontent FROM syscode " + + "WHERE type = '64' and code = '" + typeErr + "'"; + ResultSet syscodeSet = SQLHelper.ExecProcwCommands(syscodeSql); + if (syscodeSet != null) { + try { + while (syscodeSet.next()) { + content = syscodeSet.getString("content"); + encontent = syscodeSet.getString("encontent"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + String remark; + if (Work.language.equals("en")) { + remark = encontent; + } else { + remark = content; + } + // if (BusinessParameter.IsSend(terminal, typeErr)) + if (smsContent.length() == 0) { + smsContent = remark; + } else { + smsContent = smsContent + ";" + remark; + } + InsertEventInfo(time, terminal, gcomid, ccomid1, "", typeErr, remark, barcode1, "", eventid); + + return smsContent; + } + + /** + * 补数据 路 + * + * @param terminal + * @param outdata + * @param batchtime + */ + public void complementary_data(String terminal, String outdata, String batchtime) { + int lampCount = Integer.valueOf(outdata.substring(8, 10)); + List pnList = new ArrayList(); + int iStart = 10; + int pn = 0; + String str = ""; + for (int i = 0; i < lampCount; i++) { + if ((iStart + 4) >= outdata.length()) + break; + str = outdata.substring(iStart, iStart + 4); + iStart += 2; + str = str.substring(2) + str.substring(0, 2); + pn = Integer.valueOf(str, 16); + pnList.add(pn); + } + + for (int i = 0; i < lampCount; i++) { + pn = pnList.get(i); + String strsql = "select top 1 * from lampdata where terminal='" + terminal + "' and num=" + + String.valueOf(pn) + " and dataTime<'" + batchtime + "'"; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) + return; + + try { + while (rSet.next()) { + String runtime = rSet.getString("runtime"); + String datatime = batchtime; + String barcode = rSet.getString("barcode"); + String groupid = rSet.getString("groupid"); + String num = rSet.getString("num"); + String control = rSet.getString("control"); + String succeed = rSet.getString("succeed"); + String Voltage = rSet.getString("Voltage"); + String electricity = rSet.getString("electricity"); + String actpow = rSet.getString("actpow"); + String Dimming = rSet.getString("Dimming"); + String temperature = rSet.getString("temperature"); + String worktype = rSet.getString("worktype"); + + strsql = "insert into lampdata(runtime,datatime,barcode,groupid,num,control,succeed,Voltage,electricity,actpow,Dimming,temperature,worktype,dataType) " + + " values('" + runtime + "'," + "'" + datatime + "'," + "'" + barcode + "'," + groupid + + "," + num + "," + "'" + control + "'," + "'" + succeed + "'," + "'" + Voltage + "'," + "'" + + electricity + "'," + "'" + actpow + "'," + "'" + electricity + "'," + "'" + Dimming + "'," + + "'" + temperature + "'," + "'" + worktype + "'," + "0" + ")"; + SQLHelper.ExecSql(strsql); + } + } catch (Exception e) { + + } + } + } + + /** 解析主控状态事件数据 */ + public void mControlEvent(String state1, String state2, String state3, String state4, String time, String terminal, + String ccomid, int erccode, int eventid) { + + String barcode = BusinessParameter.getbarcode(ccomid); + int realyrunmode = Integer.parseInt(state1.substring(7, 8)); + int schedulerunmode = Integer.parseInt(state1.substring(6, 7)); + int realy1sta = Integer.parseInt(state1.substring(5, 6)); + int accontactor1sta = Integer.parseInt(state1.substring(2, 3)); + int programsta = Integer.parseInt(state2.substring(7, 8)); + int volitagesta = Integer.parseInt(state2.substring(6, 7)); + int controlsta = Integer.parseInt(state2.substring(5, 6)); + int commchannel = Integer.parseInt(state2.substring(4, 5)); + int scheduleinmonth = Integer.parseInt(state2.substring(3, 4)); + int scheduleinholiday = Integer.parseInt(state2.substring(2, 3)); + int scheduleinspring = Integer.parseInt(state2.substring(1, 2)); + int onoffinput = Integer.parseInt(state2.substring(0, 1)); + + int timing = Integer.parseInt(state2.substring(7, 8)); + int control = Integer.parseInt(state2.substring(6, 7)); + int realy1err = Integer.parseInt(state2.substring(5, 6)); + int accontactor1err = Integer.parseInt(state2.substring(2, 3)); + + /** 写主控状态变化事件表 */ + wmControlEvent(barcode, ccomid, terminal, time, realyrunmode, schedulerunmode, realy1sta, accontactor1sta, + programsta, volitagesta, controlsta, commchannel, scheduleinmonth, scheduleinholiday, scheduleinspring, + onoffinput, timing, control, realy1err, accontactor1err, erccode, eventid); + } + + /** (新协议)解析故障数据后写入事件解析表;加短信息发送处理 */ + public void wEventInfoNew(String state1, String state2, String time, String tcomId, int gcomId, String ccomId1, + String ccomId2, String barcode1, String barcode2, int eventid) { + int type = 0; + String remark = ""; + String ginfo = BusinessParameter.getgname(tcomId, gcomId); + String smsinfo = ""; + if (Work.language.equals("en")) + smsinfo = tcomId + "集中器下的组" + ginfo + "发生故障,故障信息为:"; + else + smsinfo = tcomId + "集中器下的组" + ginfo + "发生故障,故障信息为:"; + + if (state1.substring(0, 1).equals("1") || state1.substring(5, 6).equals("1")) { + type = 3; + if (Work.language.equals("en")) + remark = "灯泡故障"; + else + remark = "灯泡故障"; + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, eventid); + if (BusinessParameter.IsSend(tcomId, "bulb")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(2, 3).equals("1")) { + type = 5; + if (Work.language.equals("en")) + remark = "温度故障"; + else + remark = "温度故障"; + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, eventid); + if (BusinessParameter.IsSend(tcomId, "temperature")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(3, 4).equals("1") || state1.substring(7, 8).equals("1")) { + type = 4; + if (Work.language.equals("en")) + remark = "灯泡频闪故障"; + else + remark = "灯泡频闪故障"; + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, eventid); + if (BusinessParameter.IsSend(tcomId, "blink")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (!smsinfo.equals("")) {// 加发送短信息处理 + smsinfo = smsinfo.substring(0, smsinfo.length() - 1); + SendSMS(tcomId, smsinfo); + } + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/GeneralString.java b/selfDevelop/src/main/java/com/back/protocol/GeneralString.java new file mode 100644 index 0000000..892a3dd --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/GeneralString.java @@ -0,0 +1,262 @@ +/*通用字符串处理类,以376.1为基础*/ +package com.back.protocol; + + +import com.back.common.Common; + +public class GeneralString { + + /** + * 按附录A01数据格式解析数据(秒分时日(星期-月)年) + * + * @param binarys + * 二进制数据 + * @return yyyy-mm-dd hh:mm:ss + */ + public static String formatA01(String binarys) { + String[] array = binarys.split("-"); + return "20" + array[5] + "-" + Integer.toHexString(Integer.parseInt(array[4], 16) & 0x1F) + + "-" + array[3] + " " + array[2] + ":" + array[1] + ":" + array[0]; + } + /** + * 按附录A07数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA06(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + int i= Integer.parseInt(array[1], 16); + String ibitString = ""; + if ((i&0x80)>0) + ibitString = "-"; + + ibitString = ibitString + Common.dec2Hex(i & 0x7F,2) + "." + array[0]; + return ibitString; + } + /** + * 按附录A07数据格式解析数据 + * + * @param binarys + * 二进制数据 + * XXX.X + */ + public static String formatA07(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + + return array[1] + array[0].substring(0,1) + "." + array[0].substring(1) ; + } + + /** + * 按附录A09数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA08(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + int num = Integer.parseInt(array[2], 16); + String ibit = ""; + if ((num & 0x80)>0) + ibit = "-"; + ibit += Common.dec2Hex(num & 0x7F,2); + ibit = ibit + "." + array[1] + array[0]; + + return ibit; + } + /** + * 按附录A09数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA09(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + int num = Integer.parseInt(array[2], 16); + String ibit = ""; + if ((num & 0x80)>0) + ibit = "-"; + ibit += Common.dec2Hex(num & 0x7F,2); + ibit = ibit + "." + array[1] + array[0]; + + return ibit; + } + + /** + * 按附录A11数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA11(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals(array[3]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[3]+array[2]+ array[1] +"." + array[0]; + } + + /** + * 按附录A13数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA13(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals(array[3]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[3]+array[2] +"." + array[1] + array[0]; + } + /** + * 按附录A14数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA14(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals(array[3]) && array[0].equals(array[4]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[4]+array[3]+array[2] +"." + array[1] + array[0]; + } + + /** + * 按附录A15数据格式解析数据(分时日月年) + * + * @param binarys + * 二进制数据 + * @return yyyy-MM-dd hh:mm:ss + */ + public static String formatA15(String binarys) { + String[] array = binarys.split("-"); + String minute = array[0]; + String hour = array[1]; + String day = array[2]; + String month = array[3]; + String year = "20" + array[4]; + + return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":00"; + } + + /** + * 按附录A17数据格式解析数据(分时日月) + * + * @param binarys + * 二进制数据 + * @return yyyy-MM-dd hh:mm:ss + */ + public static String formatA17(String binarys) { + String[] array = binarys.split("-"); + + String year = Common.getYear(); + + return year + "-" + array[3] + "-" + array[2] + " " + array[1] + ":" + array[0] + ":00"; + } + + /** + * 按附录A25数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA25(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + + int num = Integer.parseInt(array[2], 16); + String ibit = ""; + if ((num & 0x80)>0) + ibit = "-"; + ibit += Integer.toHexString(num & 0x7F); + ibit = ibit + array[1].substring(0, 1) + "." + array[1].substring(1) + array[0]; + return ibit; + } + + /** + * 按附录A25数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA26(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[1].substring(0, 1) + "." + array[1].substring(1) + array[0]; + } + /** + * 按附录A260数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA260(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[1] + array[0].substring(0, 1) + "." + array[0].substring(1); + } + /** + * 按附录A261数据格式解析数据 + * + * @param binarys + * 二进制数据 + */ + public static String formatA261(String binarys) { + String[] array = binarys.split("-"); + + if (array[0].equals(array[1]) && array[0].equals(array[2]) && array[0].equals(array[3]) && array[0].equals("EE")) {// 无效数据不处理 + return ""; + } + + return array[3]+array[2] + array[1] + array[0].substring(0, 1) + "." + array[0].substring(1); + } + /** 返回指定字符的重复 */ + public static String Strings(int len, char c) { + StringBuffer sbf = new StringBuffer(); + int i = 0; + while (i < len) { + i += 1; + sbf.append(c); + } + return sbf.toString(); + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/LampOld.java b/selfDevelop/src/main/java/com/back/protocol/LampOld.java new file mode 100644 index 0000000..cc6e8ba --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/LampOld.java @@ -0,0 +1,553 @@ +package com.back.protocol; + +import com.back.action.Log; +import com.back.common.Common; + +public class LampOld extends Protocol { + + static String cmdcode = ""; + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /** + * 响应数据解析处理 + * + * @param cmdid + * 转发指令ID(定采指令ID为0) + * @param terminal + * 终端地址 + * @param receivedata + * 上行报文数据 + * @param state + * 抄读状态(0为正常抄读,1为不在线,2为忙,3为超时,4为GPRS服务器连接失败) + * @param comtype + * 通信类型(0001为串口,0002为GPRS) + * @param batchtime + */ + public void ResolvingData(int cmdid, String terminal, String receivedata, int state, + String comtype, String batchtime) { + if (comtype.equals("0001")) { // 串口数据解析 + if (receivedata.length() == 0) { // 超时没有应答 + if (cmdid != 0) { // 非定采数据 + wReceiveData(cmdid, terminal, receivedata, state); + } + } else { + dataExecute(cmdid, receivedata, batchtime); // + } + } else if (comtype.equals("0002")) {// GPRS 数据解析 + if (cmdid == 0) {// 定采指令响应数据解析 + if (state == 0) { + dataAnalysis(receivedata, batchtime); + } + } else {// 指令转发响应数据,直接写入结果表 + wReceiveData(cmdid, terminal, receivedata, state); + } + } + } + + /** 上行报文数据解析处理(定采响应数据和上报数据) */ + public static void dataAnalysis(String cmdcode, String batchtime) { + if (cmdcode.length() == 0) { + return; + } + + String terminal = "";// 终端地址 + int gcomid = 0;// 组地址 + String ccomid = "";// 灯地址 + + int count = 0;// 组内灯的数量 + String succeed = "";// 灯的抄读成功标识 + String status = "";// 状态 + String failure = "";// 故障 + String crctime = "";// 时间表CRC + + String[] array; + array = cmdcode.split("-"); + + for (int i = 4; i < 8; i++) { + terminal += array[i]; + } + + try { + if (array[10].equals("11") && array[11].equals("00")) {// 故障上报帧 + wEventData(terminal, "1", cmdcode, "0001"); + } else if (array[10].equals("11") && array[11].equals("10")) {// 防盗上报帧 + wEventData(terminal, "2", cmdcode, "0001"); + } else if (array[10].equals("10") && array[11].equals("71")) {// 路灯状态抄读帧 + gcomid = Common.hextoint(array[12]); + count = Integer.parseInt(array[13], 16); + if (count == 0) { + return; + } + String[] temp = new String[array.length - 19]; + System.arraycopy(array, 14, temp, 0, array.length - 19);// 数组复制 + + for (int i = 0; i < temp.length / 9; i++) { + ccomid = temp[i * 9] + temp[i * 9 + 1] + temp[i * 9 + 2] + temp[i * 9 + 3]; + succeed = temp[i * 9 + 4]; + status = temp[i * 9 + 5]; + failure = temp[i * 9 + 6]; + crctime = temp[i * 9 + 7] + temp[i * 9 + 8]; + // 定采数据解析 + analyCurData(terminal, gcomid, ccomid, succeed, status, failure, batchtime); + } + } + } catch (Exception e) { + wabnormal(terminal, cmdcode, "集中器上行报文不符合应用(不存在故障灯)!", "前置机", Common.getDateStr0()); + } + } + + /** + * 定采数据解析 + * + * @param tcomid + * 终端地址 + * @param gcomid + * 组地址 + * @param ccomid + * 灯地址 + * @param succeed + * 抄读状态 + * @param status + * 灯状态 + * @param failure + * 故障状态 + */ + public static void analyCurData(String tcomid, int gcomid, String ccomid, String succeed, + String status, String failure, String batchtime) { + + ccomid = Common.right("00000000" + ccomid, 8); + int intsucceed = Integer.parseInt(succeed);// 抄读成功标识:0为失败,1为成功 + + status = Common.hextobinary(status); + status = Common.right("00000000" + status, 8); + + int arealystate = Integer.parseInt(status.substring(7, 8)); + int brealystate = Integer.parseInt(status.substring(5, 6)); + int aschedule = Integer.parseInt(status.substring(2, 3)); + int bschedule = Integer.parseInt(status.substring(0, 1)); + int clockstate = Integer.parseInt(status.substring(1, 2)); + + failure = Common.hextobinary(failure); + failure = Common.right("00000000" + failure, 8); + + int lampstate = intsucceed;// 灯状态字标识:0表示错误,1表示正确,2表示未知 + int arealyerr = Integer.parseInt(failure.substring(6, 7)); + if (arealyerr == 1) + lampstate = 0; + int brealyerr = Integer.parseInt(failure.substring(4, 5)); + if (brealyerr == 1) + lampstate = 0; + int ablinkerr = Integer.parseInt(failure.substring(3, 4)); + if (ablinkerr == 1) + lampstate = 0; + int temperatureerr = Integer.parseInt(failure.substring(2, 3)); + int clockerr = Integer.parseInt(failure.substring(1, 2)); + int alamperr = Integer.parseInt(failure.substring(0, 1)); + if (alamperr == 1) + lampstate = 0; + + // 2011-08-08 + String srceventid = ""; + String strtemp = ""; + if (intsucceed == 1) { + if (arealyerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 1); + if (!strtemp.equals("")) { + arealyerr = 1; + lampstate = 0; + srceventid += "[arealyerr:" + strtemp + "]"; + } + } + if (brealyerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 2); + if (!strtemp.equals("")) { + brealyerr = 1; + lampstate = 0; + srceventid += "[brealyerr:" + strtemp + "]"; + } + } + if (ablinkerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 4); + if (!strtemp.equals("")) { + ablinkerr = 1; + lampstate = 0; + srceventid += "[ablinkerr:" + strtemp + "]"; + } + } + if (alamperr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 3); + if (!strtemp.equals("")) { + alamperr = 1; + lampstate = 0; + srceventid += "[alamperr:" + strtemp + "]"; + } + } + if (temperatureerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 5); + if (!strtemp.equals("")) { + temperatureerr = 1; + srceventid += "[temperatureerr:" + strtemp + "]"; + } + } + } + + // 写定采表 + wCurDataold(tcomid, gcomid, ccomid, intsucceed, lampstate, arealystate, brealystate, aschedule, + bschedule, clockstate, arealyerr, alamperr, ablinkerr, temperatureerr, clockerr, batchtime, + srceventid); + } + + /** 事件数据解析处理 加短信息发送处理 */ + public void AnalyzerData(int eventid, String time, String data) { + int type = 0;// 上报类型:1:A继电器故障,2:B继电器故障,3:A灯泡故障,4:A灯泡频闪故障,5:温度过高,6:时钟故障,7:线路防盗上报,8:B灯泡故障,9:B灯泡频闪故障 + String tcomId = "";// 集中器地址 + int gcomId = 0;// 组地址 + String ccomId1 = "";// 控制器1地址 + String ccomId2 = "";// 控制器2地址 + String barcode1 = ""; + String barcode2 = ""; + int lampid1 = 0;// 起始防盗号 + int lampid2 = 0;// 截至防盗号 + String remark = "";// 备注 + String state = "";// 故障状态字 + + String[] array = data.split("-"); + int len = data.length(); + + // 提取集中器通信地址 + tcomId = array[4] + array[5] + array[6] + array[7]; + try { + if (array[11].equals("00")) {// 故障上报1100 + // example:5B-5B-5B-5B-00-00-00-41-00-0B-11-00-01-00-00-06-8D-04-80-00-00-E1-5D-5D-5D-5D + data = data.substring(39, 39 + len - 54); + array = data.split("-"); + for (int i = 0; i < array.length / 8; i++) { + ccomId1 = array[i * 8] + array[i * 8 + 1] + array[i * 8 + 2] + array[i * 8 + 3]; + gcomId = businessParameter.getgcomid(tcomId, ccomId1); + state = array[i * 8 + 5];// 故障状态字 + state = Common.right("00000000" + Common.hextobinary(state), 8); + if (gcomId == 0) { + wabnormal(tcomId, data, "集中器上行报文不符合应用(不存在故障灯)!", "前置机", time); + } else { + wEventInfoOld(state, "", time, tcomId, gcomId, ccomId1, ccomId2, eventid); + } + } + } else {// 线路防盗1110 + // example01:5B-5B-5B-5B-00-00-00-41-00-04-11-10-01-03-D6-5D-5D-5D-5D + // example02:5B-5B-5B-5B-00-00-00-41-00-06-11-10-02-03-01-10-EA-5D-5D-5D-5D + if (len > 55) { + array = data.split("-"); + if (array[12].endsWith("01")) {// example01 + data = array[13];// 被盗组号 + gcomId = Common.hextoint(data); + type = 7; + remark = "线路被盗"; + if (gcomId == 0) { + wabnormal(tcomId, data, "集中器上行报文不符合应用(不存在被盗组)!", "前置机", time); + } else { + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, + barcode2, eventid); + } + } else { + data = data.substring(39, len - 15); + array = data.split("-"); + + for (int i = 0; i < array.length / 3; i++) { + gcomId = Common.hextoint(array[i * 3]); + lampid1 = Common.hextoint(array[i * 3 + 1]); + ccomId1 = businessParameter.getCcomid(tcomId, gcomId, lampid1); + lampid2 = Common.hextoint(array[i * 3 + 2]); + ccomId2 = businessParameter.getCcomid(tcomId, gcomId, lampid2); + type = 7; + remark = "线路被盗"; + + barcode1 = businessParameter.getbarcode(ccomId1); + barcode2 = businessParameter.getbarcode(ccomId2); + if (gcomId == 0) { + wabnormal(tcomId, data, "集中器上行报文不符合应用(不存在被盗组)!", "前置机", time); + } else { + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, + barcode2, eventid); + } + // 加发送短信息处理 + if (businessParameter.IsSend(tcomId, "steal")) { + String smsinfo = "于" + time + "发生线路被盗,地点位于" + tcomId + "集中器()下属的" + gcomId + + "号组;起始防盗序号:" + lampid1 + ",截至防盗序号:" + lampid2 + "."; + SendSMS(tcomId, smsinfo); + } + } + } + } + } + } catch (Exception e) { + wabnormal(tcomId, data, "集中器上行报文异常!", "事件数据解析", time); + } + } + + /** + * (旧协议)解析故障数据后写入事件解析表;加短信息发送处理 + * + * @param state1 + * 故障状态字1 + * @param state2 + * 故障状态字2 + * @param eventid + * 源数据ID + * + */ + public static void wEventInfoOld(String state1, String state2, String time, String tcomId, + int gcomId, String ccomId1, String ccomId2, int eventid) { + int type = 0; + String remark = ""; + String smsinfo = ""; + String barcode1 = businessParameter.getbarcode(ccomId1); + String barcode2 = businessParameter.getbarcode(ccomId2); + + if (state1.substring(0, 1).equals("1")) { + type = 3; + remark = "灯泡故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "alamperr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "bulb")) {// 检查是否发送消息 + smsinfo = remark + ","; + } + } + if (state1.substring(1, 2).equals("1")) { + type = 6; + remark = "时钟故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "clockerr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "clock")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(2, 3).equals("1")) { + type = 5; + remark = "温度故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "temperatureerr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "temperature")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(3, 4).equals("1")) { + type = 4; + remark = "灯泡频闪故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "ablinkerr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "blink")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(4, 5).equals("1")) { + type = 2; + remark = "B继电器故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "brealyerr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "brelay")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + if (state1.substring(6, 7).equals("1")) { + type = 1; + remark = "A继电器故障"; + updateCurdata(time, tcomId, gcomId, ccomId1, eventid, "arealyerr", 1); + InsertEventInfo(time, tcomId, gcomId, ccomId1, ccomId2, type, remark, barcode1, barcode2, + eventid); + if (businessParameter.IsSend(tcomId, "relay")) {// 检查是否发送消息 + smsinfo += remark + ","; + } + } + + if (!smsinfo.equals("")) {// 加发送短信息处理 + smsinfo = smsinfo.substring(0, smsinfo.length() - 1); + SendSMS(tcomId, smsinfo); + } + } + + /** + * 获取下行报文 + * + * @param terminal + * 终端地址 + * @param datas + * 具体设置的报文 + */ + public String GetSendCmd(String terminal, String datas) { + int i; + int count; + int num; + int msg[] = new int[1024]; + StringBuffer sendBuffer = new StringBuffer(); + String temp; + // 报文头 + for (i = 0; i < 4; i++) + msg[i] = 0x5B; + num = 4; + // 通信地址 + // 通信地址是16进制处理 + count = 0; + for (int j = (terminal.length() / 2) - 1; j > -1; j--) { + temp = terminal.substring(j * 2, (j * 2 + 2)); + msg[num + j] = Integer.parseInt(temp, 16) & 0xFF; + } + num += 4; + + // 数据长度 + count = datas.length() / 2; + msg[num + 1] = (count % 0x100); + count >>= 8; + msg[num] = (count); + num += 2; + + // 数据区 + count = datas.length() / 2; + for (int j = 0; j < count; j++) + msg[num + j] = Integer.parseInt(datas.substring(j * 2, (j * 2 + 2)), 16); + num += count; + + // 校验字 + count = 0; + for (int j = 0; j < num; j++) + count += msg[j]; + count = count % 0x100; + msg[num] = (count); + num++; + + // 报文结束符 + for (int j = 0; j < 4; j++) + msg[num + j] = 0x5D; + num += 4; + + // 转成字符串 + for (int j = 0; j < num; j++) + sendBuffer.append(Common.dec2Hex(msg[j], 2) + "-"); + + String cmdcode = sendBuffer.toString().substring(0, sendBuffer.toString().length() - 1); + + return cmdcode.trim(); + } + + /** + * 串口主动上报的确认处理 + * + * @param cmdid + * 指令数据ID cmdid=0 是定采数据 + * @param receivedata + * 响应数据 + */ + public void dataExecute(int cmdid, String receivedata, String batchtime) { + cmdcode += receivedata; + int indexcount = 0; + String type = ""; // 上报类型 + String cmdresult = ""; + String[] array; + String terminal; + + if (cmdcode.contains("5B-5B-5B-5B") && cmdcode.contains("5D-5D-5D-5D")) {// 旧协议处理 + + indexcount = cmdcode.indexOf("5B-5B-5B-5B"); + cmdcode = cmdcode.substring(indexcount); + + if (cmdcode.endsWith("-")) { + cmdcode = cmdcode.substring(0, cmdcode.length() - 1); + } + + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Read Comm:" + cmdcode); + + indexcount = cmdcode.indexOf("-5D-5D-5D-5D-5D"); + if (indexcount == -1) {// 校验字不为"5D" + indexcount = cmdcode.indexOf("-5D-5D-5D-5D"); + } else {// 校验字为"5D" + indexcount += 3; + } + + while (indexcount != 11 && indexcount != 0 && indexcount != -1) { + cmdresult = cmdcode.substring(0, indexcount) + "-5D-5D-5D-5D"; + array = cmdresult.split("-"); + // 提取集中器通信地址 + terminal = array[4] + array[5] + array[6] + array[7]; + if (array.length < 13) { + String time = Common.getDateStr0(); + wabnormal(terminal, cmdresult, "集中器上行报报文长度不足13个字节!", "事件数据解析", time); + return; + } + + terminal = cmdresult.substring(12, 24).replace("-", "");// 通信地址 + + if (array[0].equals("5B") && array[1].equals("5B") && array[2].equals("5B") + && array[3].equals("5B")) { + if (array[10].equals("51") && array[11].equals("23")) {// 集中器注册帧 + type = "4"; + } else if (array[10].equals("11") && array[11].equals("00")) { // 故障上报帧 + type = "1"; + } else if (array[10].equals("11") && array[11].equals("10")) { // 防盗上报帧 + type = "2"; + } else if (array[10].equals("11") && array[11].equals("20")) {// 上电请求校时 + type = "3"; + } + + if (!type.equals("4") && !type.equals("1") && !type.equals("2") && !type.equals("3")) { // 写入结果表 + if (cmdid == 0) {// 定采数据解析 + dataAnalysis(cmdresult, batchtime); + } else {// 写结果表 + wReceiveData(cmdid, terminal, cmdresult, 0); + } + } else {// 写入事件表 + wEventData(terminal, type, cmdresult, "0001"); + // 响应事件处理 + response(cmdresult, Integer.parseInt(type)); + } + } + + cmdcode = cmdcode.substring(indexcount + 12); + if (cmdcode.equals("-5D-5D-5D-5D")) { + cmdcode = ""; + } + indexcount = cmdcode.indexOf("-5D-5D-5D-5D"); + } + } + } + + /** + * 串口上报事件响应 + * + * @param strdata + * 上报事件报文 + * @param type + * 上报事件类型 + */ + public static void response(String strdata, int type) { + String data = ""; + String header = strdata.substring(0, 23);// 5B-5B-5B-5B-00-00-00-6D + + switch (type) { + case 1:// 主动上报确认 + data = "11-01"; + break; + case 2:// 线路损坏报警上报确认 + String[] array = strdata.split("-"); + if (array[12].equals("01")) { + data = "11-11-01"; + } else { + data = "11-11-02"; + } + break; + case 3:// 上电请求校时 + String time = Common.getDateStr3(); + data = "21-50-" + time; + break; + } + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/Lon16.java b/selfDevelop/src/main/java/com/back/protocol/Lon16.java new file mode 100644 index 0000000..139adc2 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/Lon16.java @@ -0,0 +1,1318 @@ +package com.back.protocol; + +import java.sql.ResultSet; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.common.MeterTimingParams; +import com.back.jdbc.SQLHelper; + +/** + * lon16 类 + * @author welcomecc + * + */ +public class Lon16 extends Protocol{ + static String cmdcode = ""; + private static String clazzName = new Object() { + public String getClassName() + { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + /** + * 获取下行报文 + * + * @param terminal + * 终端地址 + * @param datas + * 具体设置的报文 + */ + public byte[] GetSendCmd(String terminal, String datas) { + byte[] ruleByte = new byte[datas.length() + 8]; + //判断集中器的长度是不达到12位; + terminal = Common.lPad(terminal, 12, "0"); + byte[] bcd = Common.str2Bcd(terminal); + byte[] dataByte = datas.getBytes(); + + int i; + int offset = 7; + for(i=0;i<6;i++) + { + ruleByte[i] = bcd[i]; + } + ruleByte[6] = (byte)0x3B; + for(i=0;i0) + dataAnalysis(terminal,comtype,command,receivedata, batchtime,taskidString); + } + else + { + wReceiveData(cmdid, terminal, receivedata, state); + } + } else if (comtype.equals("0002")) {// GPRS 数据解析 + if (cmdid == 0) {// 定采指令响应数据解析 + if (state == 0) { + dataAnalysis(terminal,comtype,command,receivedata, batchtime,taskidString); + } + } else {// 指令转发响应数据,直接写入结果表 + wReceiveData(cmdid, terminal, receivedata, state); + } + } + + } + + /** 定采数据解释 */ + public static void dataAnalysis(String Tcomid,String comtype,String cmd,String receivedata, String batchtime,String taskidString) { + if (receivedata.length() == 0) { + return; + } + // if (comtype.equals("0002")) //GPRS 有集中器的通信地址 + // receivedata = receivedata.substring(39); + //GRBXXXXNNF0204100503 + + if (cmd.substring(0,3).equals("GRB")) + { + + //GRB命令处理 + if (dataAnalysisGRB(Tcomid,comtype,cmd,receivedata,batchtime)) + { + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + } + return; + } + //R123456789012F0204100503 + if (cmd.substring(0,1).equals("R") && cmd.subSequence(13, 14).equals("F")) + { + if(cmd.contains("F0204100503")) //GRB命令中部份补抄数据 + { //普通表 + if (dataAnalysisR(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + }else if(cmd.contains("F707110")){ //GRB命令中部份补抄数据 陕西卡表 + if (dataAnalysisShan(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + } + else + { //多费率 + if (dataAnalysisRate(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + } + + return; + } + + //R1000F0203040506070809 + if (cmd.substring(0,2).equals("R1") && cmd.subSequence(5, 6).equals("F")) + + { + if(cmd.contains("F707109")){ // 陕西卡表 + if (dataAnalysisShan(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + } else { + if (dataAnalysisMulti(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + return; + } + } + + //R3000F03040506070809 + if (cmd.substring(0,2).equals("R3")&& cmd.subSequence(5, 6).equals("F")) + { //台区表 + if (cmd.substring(0, 8).equals("R3000F03")) + {//抄电能量 + if (dataAnalysisChkM(Tcomid,comtype,cmd,receivedata,batchtime)==true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + return; + } + else + {//抄生产曲线 + if (dataAnalysisChkMIV(Tcomid,comtype,cmd,receivedata,batchtime)== true) + //删除补抄列表 + deltempmeters(Tcomid,cmd,batchtime); + return; + } + } + } + + + /** + * 解码GRB命令 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static boolean dataAnalysisGRB(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + {//GRBXXXXNNF0204100503 + MeterTimingParams params = null; + if (receivedata.contains("No Connected")) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + Tcomid+ "] 不在线!" ); + return false; + } + receivedata = Common.Ascii2Hex(receivedata); + String [] msgList = receivedata.split("2C"); + int i,j; + String meterType;//02 02(1) 抄表标志 + String readState; //04 02(1) 选抄标志 + 成功标志 + String disValue; //05 8(4) 当前有功总电量 + String readTime; //10 12(6) 自动抄表时间 + String deep; //03 02(1) 相位 + 中继深度 相位:{1,2,3}中继深度:{0,1,2,3} + String meter; //01 12(6) 电表表号 + String balanceValue; //05 8(4) 当前剩余金额 + String lastValue; //05 8(4) 当前上一次购电后累计购电金额 + + //StringBuilder sb = new StringBuilder(); + List cmdlist=new ArrayList(); + + for(i=0;i length <18 msg=" + + msg + " >> " + meterData); + continue; + } // 0204100503 + meter = meterData.substring(0, 12); + meterData = meterData.substring(12); + + meterType = meterData.substring(0, 2); + meterData = meterData.substring(2); + + readState = meterData.substring(0, 2); + meterData = meterData.substring(2); + + readTime = meterData.substring(0, 12); + readTime = "20" + readTime.substring(0, 2) + '-' + + readTime.substring(2, 4) + '-' + readTime.substring(4, 6) + + ' ' + readTime.substring(6, 8) + ':' + + readTime.substring(8, 10) + ':' + + readTime.substring(10, 12); + meterData = meterData.substring(12); + + disValue = meterData.substring(0, 8); + disValue = disValue.substring(0, 6) + '.' + + disValue.substring(6, 8); + meterData = meterData.substring(8); + + deep = meterData.substring(0, 2); + + balanceValue = meterData.substring(0, 8); + balanceValue = balanceValue.substring(0, 6) + '.' + + balanceValue.substring(6, 8); + meterData = meterData.substring(8); + + lastValue = meterData.substring(0, 8); + lastValue = lastValue.substring(0, 6) + '.' + + lastValue.substring(6, 8); + + + //20140916 增加单表补抄命令 + if ( readState.substring(1).equals("0")) + { + cmdlist.add("R" + meter + "F0204100503"); + //陕西卡表 + cmdlist.add("R" + meter + "F04707110"); + } + wdaydatas(Tcomid, batchtime.substring(0, 10), meter, disValue, + readTime, readState.substring(1)); + + wdaydataShan(Tcomid, batchtime.substring(0, 10), meter, balanceValue,lastValue, + readTime, readState.substring(1)); + + } + if ((cmdlist.size() % msgList.length) == 0) + return false; + + for( i=0;i生成补抄命令时出错:" + e.getMessage() ); + } + } + + return true; + } + /** + * 解码用户多功能报文 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static boolean dataAnalysisMulti(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { + // F03040506070809 + String meter; // 01 12(6) 电表表号 + //String meterType;// 02 02(1) 抄表标志 + String deep; // 03 02(1) 相位 + 中继深度 相位:{1,2,3}中继深度:{0,1,2,3} + String readState;// 04 02(1) 选抄标志 + 成功标志 + String disValue; // 05 8(4) 当前有功总电量 + String T1; // 06 8(4) 当前有功峰电量 + String T2; // 07 8(4) 当前有功平电量 + String T3; // 08 8(4) 当前有功谷电量 + String readTime; // 9 12(6) 自动抄表时间 + //receivedata = receivedata.replace("-", "").replace("0D0A", ""); + //receivedata = Common.HexStr2AsciiStr(receivedata); + if (receivedata.contains("No Connected")) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + Tcomid+ " ] 不在线!" ); + return false; + } + String[] msgList = receivedata.split(" "); + if (msgList.length<9) return false; + try + { + meter = msgList[0]; + //meterType = msgList[2]; + deep = msgList[2]; + readState = msgList[3]; + disValue = msgList[4]; + disValue = disValue.substring(0, 6) + '.' + disValue.substring(6, 8); + T1 = msgList[5]; + T1 = T1.substring(0, 6) + '.' + T1.substring(6, 8); + T2 = msgList[6]; + T2 = T2.substring(0, 6) + '.' + T2.substring(6, 8); + T3 = msgList[7]; + T3 = T3.substring(0, 6) + '.' + T3.substring(6, 8); + readTime = msgList[8]; + readTime = "20" + readTime.substring(0, 2) + '-' + + readTime.substring(2, 4) + '-' + readTime.substring(4, 6) + + ' ' + readTime.substring(6, 8) + ':' + + readTime.substring(8, 10) + ':' + + readTime.substring(10, 12); + wdaydatasByMulti(Tcomid, batchtime.substring(0, 10), meter, disValue,T1, T2, T3,readTime, readState.substring(1)); + return true; + }catch (Exception e) { + // TODO: handle exception + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + + } + /** + * 解码多费率报文 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static boolean dataAnalysisRate(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { + //F040607080910 + //发送命令:R0002F040607080910 + //收到数据:101503295803;102120901803 F040607080910 00 00000000 00000000 140619005321 + + String meter; //01 12(6) 电表表号 + //String meterType;//02 02(1) 抄表标志 + //String deep; //03 02(1) 相位 + 中继深度 相位:{1,2,3}中继深度:{0,1,2,3} + String readState;//04 02(1) 选抄标志 + 成功标志 + String disValue; //05 8(4) 当前有功总电量 + String T1; //06 8(4) 当前有功尖电量 + String T2; //07 8(4) 当前有功峰电量 + String T3; //08 8(4) 当前有功平电量 + String T4; //09 8(4) 当前有功谷电量 + String readTime; //10 12(6) 自动抄表时间 + //receivedata = receivedata.replace("-", "").replace("0D0A", ""); + //receivedata = Common.HexStr2AsciiStr(receivedata); + if (receivedata.contains("No Connected")) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + Tcomid+ " ] 不在线!" ); + return false; + } + + String[] msgList = receivedata.split(" "); + + if (msgList.length<8) return false; + + try + { + meter = msgList[0]; + //meterType = msgList[2]; + //deep = msgList[4]; + readState = msgList[2]; + //disValue = msgList[6]; + //disValue = disValue.substring(0, 6) + '.' + disValue.substring(6,8); + T1 = msgList[3]; + T1 = T1.substring(0, 6) + '.' + T1.substring(6,8); + T2 = msgList[4]; + T2 = T2.substring(0, 6) + '.' + T2.substring(6,8); + T3 = msgList[5]; + T3 = T3.substring(0, 6) + '.' + T3.substring(6,8); + T4 = msgList[6]; + T4 = T4.substring(0, 6) + '.' + T4.substring(6,8); + readTime = msgList[7]; + readTime = "20" + readTime.substring(0, 2) + '-' + + readTime.substring(2, 4) + '-' + readTime.substring(4, 6) + + ' ' + readTime.substring(6, 8) + ':' + + readTime.substring(8, 10) + ':' + + readTime.substring(10, 12); + wdaydatasByRate(Tcomid, batchtime.substring(0, 10),meter,T1,T2,T3,T4,readTime); + if (readState.substring(1).equals("1")) + return true; + else + return false; + }catch (Exception e) { + // TODO: handle exception + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + + } + + /** + * 陕西卡表 + * @param Tcomid + * @param comtype + * @param cmd + * @param receivedata + * @param batchtime + * @return + */ + public static boolean dataAnalysisShan(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { + //F02707109 或 F04707110 + //发送命令:R0002F02707110 R1000F04707109 + //收到数据:101503295803 F04707109 01 00000000 00000000 140619005321 + + + String balanceValue; //05 8(4) 当前剩余金额 + String lastValue; //05 8(4) 当前上一次购电后累计购电金额 + String meter; //01 12(6) 电表表号 + String readState; //04 02(1) 选抄标志 + 成功标志 + String readTime; //10 12(6) 自动抄表时间 + if (receivedata.contains("No Connected")) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + Tcomid+ " ] 不在线!" ); + return false; + } + String[] msgList = receivedata.split(" "); + + if (msgList.length<6) return false; + + try + { + meter = msgList[0]; + readState = msgList[2]; + readState = readState.substring(1); + balanceValue = msgList[3]; + balanceValue = balanceValue.substring(0, 6) + '.' + balanceValue.substring(6,8); + lastValue = msgList[4]; + lastValue = lastValue.substring(0, 6) + '.' + lastValue.substring(6,8); + readTime = msgList[5]; + readTime = "20" + readTime.substring(0, 2) + '-' + + readTime.substring(2, 4) + '-' + readTime.substring(4, 6) + + ' ' + readTime.substring(6, 8) + ':' + + readTime.substring(8, 10) + ':' + + readTime.substring(10, 12); + + + wdaydataShan(Tcomid, batchtime.substring(0, 10), meter,balanceValue,lastValue, + readTime, readState); + if (readState.equals("1")) + return true; + else + return false; + }catch (Exception e) { + // TODO: handle exception + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + + } + + public static boolean dataAnalysisR(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { + //F0204100503 + //发送命令:R0002F04100503 + //收到数据:101503295803;04100503 F02080910 00 00000000 00000000 140619005321 + + String meterType;//02 02(1) 抄表标志 + String readState; //04 02(1) 选抄标志 + 成功标志 + String disValue; //05 8(4) 当前有功总电量 + String readTime; //10 12(6) 自动抄表时间 + String deep; //03 02(1) 相位 + 中继深度 相位:{1,2,3}中继深度:{0,1,2,3} + String meter; //01 12(6) 电表表号 + //receivedata = receivedata.replace("-", "").replace("0D0A", ""); + //receivedata = Common.HexStr2AsciiStr(receivedata); + if (receivedata.contains("No Connected")) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + Tcomid+ " ] 不在线!" ); + return false; + } + String[] msgList = receivedata.split(" "); + + if (msgList.length<7) return false; + + try + { + meter = msgList[0]; + meterType = msgList[2]; + + readState = msgList[3]; + readTime = msgList[4]; + readTime = "20" + readTime.substring(0, 2) + '-' + + readTime.substring(2, 4) + '-' + readTime.substring(4, 6) + + ' ' + readTime.substring(6, 8) + ':' + + readTime.substring(8, 10) + ':' + + readTime.substring(10, 12); + disValue = msgList[5]; + disValue = disValue.substring(0, 6) + '.' + disValue.substring(6,8); + deep = msgList[6]; + + wdaydatas(Tcomid, batchtime.substring(0, 10), meter, disValue, + readTime, readState.substring(1)); + if (readState.substring(1).equals("1")) + return true; + else + return false; + }catch (Exception e) { + // TODO: handle exception + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + + } + + /** + * 保存普通表抄表数据 + * @param terminal 集中器通信地址 + * @param datadate 数据日期 + * @param meterid 电表通信地址 + * @param value 正向有功表示数 + * @param fieldtime 抄读时间 + */ + + public static void wdaydatas(String terminal,String datadate,String meterid,String value,String fieldtime,String succeed) + { + int i = 0; + String strsql = "select count(1) count from daydatas where terminal='" + terminal + "' " + + " and datadate='" + datadate + "' and meter='" + meterid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i>0) //更新 + { + strsql = "update daydatas set foracttime ='" + fieldtime + "', foract='" + value + "',succeed='" + succeed + "',computertime='" + wtime + "'" + + " where terminal ='" + terminal + + "' and datadate = '" + datadate +"' and meter='" + meterid + "'"; + } + else + { + + //写入与更新分开,可以保证。集中器内的新表数据,可以保存下来。 + strsql = "insert into daydatas(terminal,datadate,meter,comid,foracttime,foract,succeed,computertime,no) " + + " values('" + terminal + "' ,'" + datadate + "','" + meterid + "','" + meterid + "','" + + fieldtime + "','" + value + "','" + succeed + "','" + wtime + "',0);"; + strsql += "update daydatas set daydatas.userid=m.userid,daydatas.username=m.username,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types,daydatas.multiple=m.multiple from daydatas, meters m where daydatas.terminal=m.terminal and daydatas.meter=m.comid" + + " and daydatas.meter='"+meterid+"'" + + " and daydatas.datadate='" + datadate + "';"; + + } + SQLHelper.ExecSql(strsql); + + // 更新表记电量 + if (succeed.equals("1")) + CalculateHappen(datadate,meterid); + + //strsql = "update daydatas set happen= isnull((cast(foract as numeric)-(SELECT max(cast(foract as numeric)) FROM daydatas WHERE foracttime0) //更新 + { + strsql = "update daydatas set foracttime ='" + fieldtime + "', balance='" + balanceValue + "', lastbalance ='" + lastValue + "',succeed='" + succeed + "',computertime='" + wtime + "'" + + " where terminal ='" + terminal + + "' and datadate = '" + datadate +"' and meter='" + meterid + "'"; + } + else + { + + //写入与更新分开,可以保证。集中器内的新表数据,可以保存下来。 + strsql = "insert into daydatas(terminal,datadate,meter,comid,foracttime,balance,lastbalance,succeed,computertime) " + + " values('" + terminal + "' ,'" + datadate + "','" + meterid + "','" + meterid + "','" + + fieldtime + "','" + balanceValue + "','" + lastValue + "','" + succeed + "','" + wtime + "');"; + /* + strsql += "update daydatas set daydatas.userid=m.userid,daydatas.username=m.username,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types,daydatas.multiple=m.multiple from daydatas, meters m where daydatas.terminal=m.terminal and daydatas.meter=m.comid" + + " and daydatas.meter='"+meterid+"'" + + " and daydatas.datadate='" + datadate + "';"; + */ + + } + SQLHelper.ExecSql(strsql); + + + } + + /** + * 保存普通表(多费率)抄表数据 + * @param terminal 集中器通信地址 + * @param datadate 数据日期 + * @param meterid 电表通信地址 + * @param fa1 正向有功表示数 + * @param fieldtime 抄读时间 + */ + + public static void wdaydatasByRate(String terminal,String datadate,String meterid,String fa1,String fa2,String fa3,String fa4,String fieldtime) + { + int i = 0; + String strsql = "select count(1) count from daydatas where terminal='" + terminal + "' " + + " and datadate='" + datadate + "' and meter='" + meterid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i>0) //更新 + { + strsql = "update daydatas set foracttime ='" + fieldtime + "', " + + "fa1='" + fa1 + "',fa2='" + fa2 + "',fa3='" + fa3 + "',fa4='" + fa4 + "',computertime='" + wtime + "'" + + " where terminal ='" + terminal + + "' and datadate = '" + datadate +"' and meter='" + meterid + "'"; + } + else + { + strsql = "insert into daydatas(terminal,datadate,meter,foracttime,fa1,fa2,fa3,fa4,computertime) " + + " values('" + terminal + "' ,'" + datadate + "','" + meterid + "'," + + "'" + fieldtime + "','" + fa1 + "','" + fa2 + "','" + fa3 + "','" + fa4 + "','" + wtime +"');"; + // 从meters表更新daydatas + //strsql += "update daydatas set daydatas.userid=m.recordid,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.comid=m.comid,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types from daydatas, meters m where daydatas.terminal=m.terminal and daydatas.meter=m.comid;"; + } + SQLHelper.ExecSql(strsql); + + + // 更新表记电量 + + //strsql = "update daydatas set happen= isnull((cast(foract as numeric)-(SELECT max(cast(foract as numeric)) FROM daydatas WHERE foracttime0) //更新 + { + strsql = "update daydatas set foracttime ='" + fieldtime + "', foract='" + foract + "',succeed='" + succeed + "',computertime='" + wtime + "'" + +" ,fa3='" + fa3 + "',fa4='" + fa4 +"',forreact ='" + forreact + "'" + + " where terminal ='" + terminal + + "' and datadate = '" + datadate +"' and meter='" + meterid + "'"; + } + else + { + + //写入与更新分开,可以保证。集中器内的新表数据,可以保存下来。 + strsql = "insert into daydatas(terminal,datadate,meter,foracttime,foract,fa3,fa4,forreact,succeed,computertime) " + + " values('" + terminal + "' ,'" + datadate + "','" + meterid + "'," + + "'" + fieldtime + "','" + foract + "','" + fa3 + "','" + fa4 + "','" + forreact + "','" + succeed + "','" + wtime + "');"; + strsql += "update daydatas set daydatas.userid=m.recordid,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.comid=m.comid,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types,daydatas.multiple=m.multiple from daydatas, meters m where daydatas.terminal=m.terminal and daydatas.meter=m.comid and daydatas.meter='"+meterid+"';"; + + + + } + SQLHelper.ExecSql(strsql); + + //更新表计电量 + if (succeed.equals("1")) + CalculateHappen(datadate,meterid); + + } + /** + * 计算用电量 + * @param datadate + * @param meterid + */ + public static void CalculateHappen( String datadate,String meterid) + { + String strsql = "SELECT happen,power(10,digit) full1,multiple,preday from " + + " (SELECT " + + "isnull( " + + "(cast(foract as decimal(8,2))-(" + + "SELECT cast(foract as decimal(8,2))" + + " FROM daydatas" + + " WHERE " + + " datadate=( " + + " select max(datadate) from daydatas e where e.meterid=d.meterid " + + "and datadate < d.datadate) and meterid=d.meterid) " + + "),0) happen,d.digit,d.multiple" + + ",(select max(f.datadate) from daydatas f where f.meterid=d.meterid and f.datadate < d.datadate and f.succeed='1' ) preday " + + " FROM daydatas d" + + " where d.meterid='" + meterid + "' and d.datadate='" + datadate + "'" + + ") a"; + + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + double happen = 0.0 ; + double full = 0.0; + double multiple = 1; + + String preDay =""; + if (rSet == null) { + return; + } + + try { + while (rSet.next()) { + happen = rSet.getDouble("happen"); + full = rSet.getDouble("full1"); + multiple = rSet.getDouble("multiple"); + preDay = rSet.getString("preday"); + + } + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + if (happen==0) + return; + if (happen<0) + { + happen = (happen + full) * multiple; + } + else + { + happen = happen * multiple; + } + + if (preDay!=null) + { + int days = 1; + try { + days = daysBetween(preDay,datadate); + happen = happen / days; + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + //电量平摊 + DecimalFormat df = new DecimalFormat("00.00"); + if (days==1) + strsql = "update daydatas set happen=" + df.format(happen) + "" + + " where datadate = '" + datadate +"' and meter='" + meterid + "'"; + else + strsql = "update daydatas set happen=" + String.valueOf(happen) + "" + + " where datadate > '" + preDay +"' and datadate <= '" + datadate +"' and meter='" + meterid + "'"; + + } + else + { + strsql = "update daydatas set happen=" + String.valueOf(happen) + "" + + " where datadate = '" + datadate +"' and meter='" + meterid + "'"; + + } + SQLHelper.ExecSql(strsql); + } + /** + * 解码台区多功能的电能数据 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static boolean dataAnalysisChkM(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { //R3000F03040506070809 + String meter; //01 12(6) 电表表号 + String deep; //03 02(1) 相位 + 中继深度 相位:{1,2,3}中继深度:{0,1,2,3} + String readState;//04 02(1) 正向电量抄读成功标志 + String disValue; //05 8(4) 正向有功总电量 + String T1; //06 8(4) 有功A相电量 + String T2; //07 8(4) 有功B相电量 + String T3; //08 8(4) 正向无功总电量 + String readTime; //10 12(6) 正向电量抄读时间 + receivedata = receivedata.replace("-", "").replace("0D0A", ""); + receivedata = Common.HexStr2AsciiStr(receivedata); + // String tcomid = receivedata.substring(0,12); + + // receivedata = receivedata.substring(13); + String[] msgList = receivedata.split(" "); + if (receivedata.contains("NO")) + return true; + if (receivedata.contains("No Connected")) + return false; + if (msgList.length<8) return false; + try + { + meter = msgList[0]; + deep = msgList[2]; + readState = msgList[3]; + disValue = msgList[4]; + disValue = disValue.substring(0, 6) + '.' + disValue.substring(6,8); + T1 = msgList[5]; + T1 = T1.substring(0, 6) + '.' + T1.substring(6,8); + T2 = msgList[6]; + T2 = disValue.substring(6, 6) + '.' + T2.substring(6,8); + T3 = msgList[7]; + T3 = T3.substring(6, 6) + '.' + T3.substring(6,8); + readTime = msgList[8]; + readTime = "20" + readTime.substring(0,2) + '-' + readTime.substring(2,4) + '-' + readTime.substring(4,6) + ' ' + + readTime.substring(6,8) + ':' + readTime.substring(8,10) + ':' + readTime.substring(10,12); + + wdaydatas(Tcomid, batchtime.substring(0, 10), meter, disValue, readTime,readState.substring(1)); + return true; + }catch(Exception e) + { + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + } + /** + * 解码台区多功能的生产数据 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static boolean dataAnalysisChkMIV(String Tcomid,String comtype,String cmd,String receivedata, String batchtime) + { + //发送命令:R3000F404142434445 + //收到数据:101503295803;103308595603 F404142434445 122220175282292962831282050985090974140619001109 132229259231231522950128040939090929140619001115 142228268200290097379168040891080833140619001117 152226254201201109588186030915080888140619001124 162225258221200086303196040890080848140619001126 172224226271210094962141030886090899140619001132 + receivedata = receivedata.replace("-", "").replace("0D0A", ""); + receivedata = Common.HexStr2AsciiStr(receivedata); + + String[] msgList = receivedata.split(" "); + + String meterid= msgList[0]; + String sUA, sUB, sUC, sDate,sIA, sIB, sIC, sI0, sCOSA, sCOSB, sCOSC; + String sHour; + + try + { + for(int i=2;i解码时出错:" + e.getMessage() + "\r\n 报文" + receivedata); + return false; + } + } + /** 写或更新曲线表 */ + public static void wdatas(String terminal, String meterid, String datetime, + String sUA,String sUB,String sUC,String sIA,String sIB,String sIC,String sCOSA,String sCOSB,String sCOSC,String sI0, + String batchtime) + { + int i = 0; + String strsql = "select count(1) count from datas where terminal='" + terminal + "' and datatime='" + datetime + "'" + + " and meterid='" + meterid + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i>0) //更新 + { + strsql = "update datas set avol='" + sUA + "',bvol='" + sUB + "',cvol='" + sUC + "'," + + "acur='" + sIA + "',bcur='" + sIB + "',ccur='" + sIC + "'," + + "zeroseqcur='" + sI0 + "'," + + "aCos='" + sCOSA + "',bCos='" + sCOSB + "',cCos='" + sCOSC + "',computertime='" +wtime + "'" + + " where terminal='" + terminal + "' and datatime='" + datetime + "'" + + " and meterid='" + meterid + "'"; + } + else + { + //没有写集中器信息 + /* + strsql = "insert into datas(avol,bvol,cvol,acur,bcur,ccur,actpow,aCos,bCos,cCos) " + + " values('" + sUA + "','" + sUB + "','" + sUC + "'," + + "'" + sIA + "','" + sIB + "','" + sIC + "'," + + "'" +sP +"'," + + "'" + sCOSA + "','" + sCOSB + "','" + sCOSC + "')"; + */ + strsql = "insert into datas(avol,bvol,cvol,acur,bcur,ccur,zeroseqcur,aCos,bCos,cCos,terminal,datatime,computertime,comid,meterid,batchtime) " + + " select '" + sUA + "','" + sUB + "','" + sUC + "'," + + "'" + sIA + "','" + sIB + "','" + sIC + "'," + + "'" +sI0 +"'," + + "'" + sCOSA + "','" + sCOSB + "','" + sCOSC + "'" + + ",terminal,'" + datetime +"','"+ wtime+ "',comid,meterid,'" + batchtime +"'" + + " from meters where comid='" +meterid + "'"; + + + } + SQLHelper.ExecSql(strsql); + } + /** + * 解码多费率 + * @param cmd + * @param receivedata + * @param batchtime + */ + public static void dataAnalysisM(String cmd,String receivedata, String batchtime) + { + + } + + + + /** + * 定采数据解析 + * + * @param tcomid + * 终端地址 + * @param gcomid + * 组地址 + * @param ccomid + * 灯地址 + * @param succeed + * 抄读状态 + * @param status + * 灯状态 + * @param failure + * 故障状态 + */ + public static void analyCurData(String tcomid, int gcomid, String ccomid, String succeed, String status, String failure, String batchtime) { + + ccomid = Common.right("00000000" + ccomid, 8); + int intsucceed = Integer.parseInt(succeed);// 抄读成功标识:0为失败,1为成功 + + status = Common.hextobinary(status); + status = Common.right("00000000" + status, 8); + + int arealystate = Integer.parseInt(status.substring(7, 8)); + int brealystate = Integer.parseInt(status.substring(5, 6)); + int aschedule = Integer.parseInt(status.substring(2, 3)); + int bschedule = Integer.parseInt(status.substring(0, 1)); + int clockstate = Integer.parseInt(status.substring(1, 2)); + + failure = Common.hextobinary(failure); + failure = Common.right("00000000" + failure, 8); + + int lampstate = intsucceed;// 灯状态字标识:0表示错误,1表示正确,2表示未知 + int arealyerr = Integer.parseInt(failure.substring(6, 7)); + if (arealyerr == 1) + lampstate = 0; + int brealyerr = Integer.parseInt(failure.substring(4, 5)); + if (brealyerr == 1) + lampstate = 0; + int ablinkerr = Integer.parseInt(failure.substring(3, 4)); + if (ablinkerr == 1) + lampstate = 0; + int temperatureerr = Integer.parseInt(failure.substring(2, 3)); + int clockerr = Integer.parseInt(failure.substring(1, 2)); + int alamperr = Integer.parseInt(failure.substring(0, 1)); + if (alamperr == 1) + lampstate = 0; + + // 2011-08-08 + String srceventid = ""; + String strtemp = ""; + if (intsucceed == 1) { + if (arealyerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 1); + if (!strtemp.equals("")) { + arealyerr = 1; + lampstate = 0; + srceventid += "[arealyerr:" + strtemp + "]"; + } + } + if (brealyerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 2); + if (!strtemp.equals("")) { + brealyerr = 1; + lampstate = 0; + srceventid += "[brealyerr:" + strtemp + "]"; + } + } + if (ablinkerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 4); + if (!strtemp.equals("")) { + ablinkerr = 1; + lampstate = 0; + srceventid += "[ablinkerr:" + strtemp + "]"; + } + } + if (alamperr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 3); + if (!strtemp.equals("")) { + alamperr = 1; + lampstate = 0; + srceventid += "[alamperr:" + strtemp + "]"; + } + } + if (temperatureerr == 0) { + strtemp = businessParameter.getEventInfoValue(ccomid, 5); + if (!strtemp.equals("")) { + temperatureerr = 1; + srceventid += "[temperatureerr:" + strtemp + "]"; + } + } + } + + // 写定采表 + wCurDataold(tcomid, gcomid, ccomid, intsucceed, lampstate, arealystate, brealystate, aschedule, bschedule, clockstate, arealyerr, alamperr, ablinkerr, temperatureerr, clockerr, batchtime, + srceventid); + } + /** + * 写电表补抄记录 + * @param terminal + * @param cmdCod + * @param comtype + * @param td + * @param intervalTiming 补抄间隔 + * @throws InterruptedException + */ + public static void wtempmeters(String terminal, String cmdCod, String comtype, String td,int intervalTiming) throws InterruptedException { + int i = 0; + //td = td.replace("-", ""); //2011-11-26 wwb 防止'01-11-11'格式的写入 + if (cmdCod ==null || cmdCod.equals("") ) //2011-12-24 wwb 防止非定采任务写到补抄表中 + return; + String strsql = "select count(1) count from tempmeters where terminal='" + terminal + "' and code='" + cmdCod + "' and td='" + td + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + //System.err.println("Protocol-->wtempmeters:strsql=" + strsql + ";i=" + i); + + SimpleDateFormat format = new SimpleDateFormat("HH:mm"); + //更新下一次运行时间,以及补抄运行次数 + String[] arrayHM = td.substring(11).split(":"); + Calendar calendar = Calendar.getInstance(); + calendar.set(0, 0, 0, Integer.parseInt(arrayHM[0].trim()), Integer.parseInt(arrayHM[1].trim())); + //calendar.add(calendar.MINUTE, intervalTiming); + String runTime = format.format(calendar.getTime()); + runTime = Common.getDateStr7() + " " + runTime + ":00"; + + + if (i == 0) { + strsql = "insert into tempmeters(terminal,code,commodel,td,count,intervalTiming,runTime,wtime,protocol) values('" + terminal + "','" + cmdCod + "','" + comtype + "','" + td + "',1,"+String.valueOf(intervalTiming)+"" + + ",'" + runTime + "','" + td + "','0001')"; + } else { + strsql = "update tempmeters set count=count+1 where terminal='" + terminal + "' and code='" + cmdCod + "' and td='" + td + "'"; + } + SQLHelper.ExecSql(strsql); + + } + /** + * 抄读成功后,删除相应补抄记录(lon16) + * @param terminal + * @param cmdCode + * @param td + */ + public static void deltempmeters(String terminal, String cmdCode, String td) { + String strsql = "delete from tempmeters where terminal='" + terminal + "' and code='" + cmdCode + "' and td='" + td + "'"; + Log.writelog(Lon16.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" +terminal +"] RunSQL:" + strsql); + SQLHelper.ExecSql(strsql); + } + + + /** + * 计算两个日期之间相差的天数 + * @param smdate 较小的时间 + * @param bdate 较大的时间 + * @return 相差天数 + * @throws ParseException + */ + public static int daysBetween(Date smdate,Date bdate) throws ParseException + { + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + smdate=sdf.parse(sdf.format(smdate)); + bdate=sdf.parse(sdf.format(bdate)); + Calendar cal = Calendar.getInstance(); + cal.setTime(smdate); + long time1 = cal.getTimeInMillis(); + cal.setTime(bdate); + long time2 = cal.getTimeInMillis(); + long between_days=(time2-time1)/(1000*3600*24); + + return Integer.parseInt(String.valueOf(between_days)); + } + + /** + *字符串的日期格式的计算 + */ + public static int daysBetween(String smdate,String bdate) throws ParseException{ + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + cal.setTime(sdf.parse(smdate)); + long time1 = cal.getTimeInMillis(); + cal.setTime(sdf.parse(bdate)); + long time2 = cal.getTimeInMillis(); + long between_days=(time2-time1)/(1000*3600*24); + + return Integer.parseInt(String.valueOf(between_days)); + } +} diff --git a/selfDevelop/src/main/java/com/back/protocol/Protocol.java b/selfDevelop/src/main/java/com/back/protocol/Protocol.java new file mode 100644 index 0000000..be3a80f --- /dev/null +++ b/selfDevelop/src/main/java/com/back/protocol/Protocol.java @@ -0,0 +1,1448 @@ +package com.back.protocol; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.communication.SendSMS; +import com.back.communication.Wechat; +import com.back.communication.mail.MailSenderInfo; +import com.back.communication.mail.SimpleMailSender; +import com.back.jdbc.SQLHelper; + +public class Protocol { + // ------------------------------------------------------------------解码通用函数------------------------------------------------------------------------------------ + public static GeneralString generalString = new GeneralString(); + // ------------------------------------------------------------------系统参数函数------------------------------------------------------------------------------------ + public static SystemParameter systemParameter = new SystemParameter(); + // ------------------------------------------------------------------业务参数函数------------------------------------------------------------------------------------ + public static BusinessParameter businessParameter = new BusinessParameter(); + + private static String clazzName = new Object() { + public String getClassName() { + String clazzName = this.getClass().getName(); + return clazzName.substring(0, clazzName.lastIndexOf('$')); + } + }.getClassName(); + + static String language = ""; + + public void Setlanguage(String language) { + this.language = language; + } + + /* + * 更新灯控器状态UpdateLampOnState terminal集中器通信ID comid 灯具终端ID state 开关灯状态 =1开灯状态 + * =0关灯状态 + */ + public static void UpdateLampOnState(String terminal, String comid, int state) { + if (state > 0) + state = 1; + String strsql = "update controls set state=" + String.valueOf(state) + " where terminal='" + terminal + + "' and comid='" + comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /* + * 更新灯控器手自动状态UpdateLampRunState terminal集中器通信ID comid 灯具终端ID Controlstate + * 开关灯状态 =1手动状态 =0自动状态 + */ + public static void UpdateLampHandState(String terminal, String comid, int Controlstate) { + if (Controlstate > 0) + Controlstate = 1; + String strsql = "update controls set controlstate=" + String.valueOf(Controlstate) + " where terminal='" + + terminal + "' and comid='" + comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /* + * 更新主控设备欠载状态 + */ + public static void UpdateMControlUnderloadState(String terminal, String comid, int state) { + if (state > 0) + state = 1; + String strsql = "update MControls set Underload=" + String.valueOf(state) + " where terminal='" + terminal + + "' and comid='" + comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** 写事件明细表(EventInfo) */ + public static void InsertEventInfo(String time, String terminal, int group, String control1, String control2, + int type, String remark, String barcode1, String barcode2, int eventid) { + // 2011-03-16:lixw:抄读成功率计算方式修改:12点之前算上天 + Date dt = new Date(); + GregorianCalendar gc = new GregorianCalendar(); + String counttime = ""; + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + dt = format.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + } + + format = new SimpleDateFormat("yyyy-MM-dd"); + if (dt.getHours() < 12) { + gc.setTime(dt); + gc.add(5, -1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE)); + counttime = format.format(gc.getTime()); + } else { + counttime = format.format(dt); + } + format = null; + gc = null; + dt = null; + + String strsql = "INSERT INTO EventInfo(wtime,terminal,groupid,control1,type,remark,status,barcode1,barcode2,counttime,eventid)VALUES('" + + time + "','" + terminal + "','" + group + "','" + control1 + // + "','" + // + control2 + + "','" + type + "','" + remark + "','" + "0" // 读取状态 =0 未读取 + // =1已读取 + + "','" + barcode1 + "','" + barcode2 + "','" + counttime + "'," + eventid + ")"; + int result = SQLHelper.ExecSql(strsql); + if (result > 0) { + /* 更新设备信息故障字 */ + if ((type > 40) && (type < 80))// 回路事件 + updateMControlEventId(terminal, control1, eventid, time); + else if ((type > 80) && (type < 100))// 配电箱状态变化事件 + updateTerminalEventId(terminal, eventid);// 更新集中器 + else if ((type > 120) && (type < 140))// 配电箱电气故障事件 + updateTerminalEventId(terminal, eventid);// 更新集中器 + else if (type == 141)// 线路被盗事件 + { + } else if ((type > 100) && (type < 120))// 传感器故障事件 + { + + } else if ((type > 0) && (type < 40))// 灯具故障事件 + { + // updateConEventId1(control1, eventid); // 灯控器通迅恢复 + updateConEventId(control1, eventid);// 更新controls表的eventid字段 + } + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write the event table operation is successful"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写事件表操作成功"); + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write the event table operation failed"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写事件表操作失败"); + } + } + + /** 更新光感数表读取标识 */ + public static void updateLightSensor(String terminal, int commandid) { + String strsql = "update lightsensordata set ReadStatus=1,rtime='" + Common.getDateStr0() + "' where id=" + + commandid; + int result = SQLHelper.ExecSql(strsql); + switch (result) { + case -1: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the sensor table data state: failed to update"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:更新失败"); + break; + case -2: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the sensor table data state: failed to connect to the database."); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:连接数据库失败"); + break; + default: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Updated sensor table data status: success"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:更新成功"); + break; + } + strsql = "delete from lightsensordata WHERE (substring(wtime,1,10) <= convert(VARCHAR(10),getdate()-1,121))"; + SQLHelper.ExecSql(strsql); + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "] sensor table data status: success"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + "]删除光感数据表状态:更新成功"); + + } + + /** 更新光感和车流量表读取标识 */ + public static void updateLightSensorAndTraffics(String terminal, int commandid, String Dimmer) { + // String strsql = "update lightsensordata1 set ReadStatus=1,rtime='" + + // Common.getDateStr0() + // + "' where id=" + commandid; + String strsql = "update lightsensordata1 set ReadStatus=1,rtime='" + Common.getDateStr0() + "',Dimmer ='" + + Dimmer + "' where id=" + commandid; + int result = SQLHelper.ExecSql(strsql); + switch (result) { + case -1: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the sensor table data state: failed to update"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:更新失败"); + break; + case -2: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the sensor table data state: failed to connect to the database."); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:连接数据库失败"); + break; + default: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Updated sensor table data status: success"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新光感数据表状态:更新成功"); + break; + } + strsql = "delete from lightsensordata1 WHERE (substring(wtime,1,10) <= convert(VARCHAR(10),getdate()-1,121))"; + SQLHelper.ExecSql(strsql); + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "] sensor table data status: success"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + "]删除光感数据表状态:更新成功"); + + } + + /** 更新指令表读取标识 */ + public static void updateCommands(String terminal, int commandid) { + + System.out.println("\nGPRS更新指令表:"); + String strsql = "update commands set status=1,rtime='" + Common.getDateStr0() + "' where CommandID = " + commandid; + int result = SQLHelper.ExecSql(strsql); + // Log.writelog(Protocol.clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + // + + // "->[" +strsql); + // int result = SQLHelper.ExecProcwCommands(commandid); + switch (result) { + case -1: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the instruction table data state: failed to update"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:更新失败"); + break; + case -2: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Update the instruction table data state: failed to connect to the database."); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:连接数据库失败"); + break; + default: + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Updated instruction table data status: success"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]更新指令表数据状态:更新成功"); + break; + } + } + + /** 修改EventData表处理标识 */ + public static void ModifyEventData(int eventid) { + String strsql = "update Eventdata SET Status =1 WHERE EventID=" + eventid; + SQLHelper.ExecSql(strsql); + } + + // ------------------------------------------------------------------短信业务处理函数------------------------------------------------------------------------------------ + /** + * 发送短信息 + * + * @param terminal + * 通信地址 + * @param msg + * 信息内容 + */ + public static void SendMail(String terminal, String msg) { + MailSenderInfo mailInfo = new MailSenderInfo(); + // 通明专用 + + mailInfo.setMailServerHost("smtp.163.com"); + mailInfo.setMailServerPort("25"); + mailInfo.setValidate(true); + mailInfo.setUserName("tongming111111@163.com"); + mailInfo.setPassword("tmdq56909999");// 您的邮箱密码 zjtm56909999 + mailInfo.setFromAddress("tongming111111@163.com"); + + // mailInfo.setMailServerHost("smtp.163.com"); + // mailInfo.setMailServerPort("25"); + // mailInfo.setValidate(true); + // mailInfo.setUserName("hq_yp@163.com"); + // mailInfo.setPassword("wwb@0755");// 您的邮箱密码 + // mailInfo.setFromAddress("hq_yp@163.com"); + + SimpleMailSender sms = new SimpleMailSender(); + + String line = businessParameter.getLine(terminal); + String strsql = "select mail from SmsInform where Line='" + line + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + String mail = ""; + try { + while (rSet.next()) { + mail = rSet.getString("mail"); + if (mail == null) + continue; + if (mail.trim().equals("")) + continue; + mailInfo.setToAddress(mail); + mailInfo.setSubject("MESSAGE"); + mailInfo.setContent(msg); + // 发送邮件 + + sms.sendTextMail(mailInfo);// 发送文体格式 + + // sms.sendHtmlMail(mailInfo);// 发送html格式 + + } + } catch (Exception e) { + return; + } + + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 发送短信息 + * + * @param terminal + * 通信地址 + * @param msg + * 信息内容 + */ + + public static void SendWachat(String terminal, String msg) { + + msg = Common.getDateStr0() + "\r\n" + msg; + String line = businessParameter.getLine(terminal); + String strsql = "select Wachat from SmsInform where Line='" + line + "'"; + java.sql.Statement stmt = null; + + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + while (rSet.next()) { + String Wachat = rSet.getString("Wachat"); + Wechat.sendMessage(Wachat, msg); + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->The message is sent successfully:" + Wachat + ":" + msg); + } + } catch (SQLException e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 发送短信息 + * + * @param terminal + * 通信地址 + * @param msg + * 信息内容 + */ + + public static void SendSMS(String terminal, String msg) { + + String phone = ""; + + String pducenter = "";// PDU编码 + String pducode = "";// PDU编码 + + String serialport = systemParameter.smsport();// 短信猫连接串口 + if (serialport.trim().equals("")) {// 未设置短信猫连接串口时直接退出 + return; + } + + String smsset = systemParameter.getSmsParams();// 短信猫串口参数 + if (smsset.equals("")) { + return; + } + String center = systemParameter.getenter();// 获取短信信息中心号码 + if (center.equals("")) { + return; + } + int maxcount = systemParameter.getmaxCount();// 获取短信息最大发送次数 + // 获取接收短信手机号码 + String line = businessParameter.getLine(terminal); + String strsql = "select phone from SmsInform where Line='" + line + "'"; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + + SendSMS sender = new SendSMS(center, serialport, 2);// SIM卡所在地短信中心号码、端口号、SIM卡类型默认2即可 + + try { + while (rSet.next()) { + phone = rSet.getString("phone"); + if (phone.trim() == "") + continue; + int code = sender.sendSMS(phone, msg);// 接收号码、内容 + if (code == 1) { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->The message is sent successfully:" + phone + ":" + msg); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->信息发送成功:" + phone + ":" + msg); + } + + } + + } catch (SQLException e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + } + + // ------------------------------------------------------------------业务处理函数------------------------------------------------------------------------------------ + /** + * 更新controls表的eventid字段 + * + * @param ccomid + * 灯地址 + * @param eventid + * 事件id + */ + public static void updateConEventId(String ccomid, int eventid) { + String strsql = "update controls set eventid=" + eventid + " WHERE comid= '" + ccomid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** + * 更新controls表的Online字段 + * + * @param ccomid + * 灯地址 + * @param Online + * 设备在线状态 + */ + public static void updateConOnline(String ccomid, int Online) { + String strsql = "update controls set online=" + Online + " WHERE comid= '" + ccomid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** + * 更新controls表的eventid字段 + * + * @param ccomid + * 灯地址 + * @param eventid + * 事件id + */ + public static void updateConEventId1(String ccomid, int eventid) { + String strsql = "SELECT count(*) num FROM controls , EventInfo WHERE controls.eventid=EventInfo.eventid and comid= '" + + ccomid + "'"; + + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + int i = 0; + try { + rSet.next(); + i = rSet.getInt("num"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + + java.sql.Statement stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + if (i == 0) + return; + + strsql = "update controls set eventid=0 WHERE comid= '" + ccomid + "'"; + SQLHelper.ExecSql(strsql); + } + + /*** + * 更新集中器表的eventid字段 + * + * @param terminal + * @param eventid + */ + public static void updateTerminalEventId(String terminal, int eventid) { + String strsql = "update terminals set eventid=" + eventid + " WHERE comid= '" + terminal + "'"; + SQLHelper.ExecSql(strsql); + } + + /** 2011-08-08:根据主动上报故障数据更新定采数据 */ + public static void updateCurdata(String time, String terminal, int group, String control, int eventid, + String fieldname, int value) { + Date dt = new Date(); + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + dt = format.parse(time); + } catch (ParseException e) { + e.printStackTrace(); + } + + String starttime = ""; + String endtime = ""; + GregorianCalendar gc = new GregorianCalendar(); + if (dt.getHours() < 12) { + gc.setTime(dt); + gc.add(5, -1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + starttime = format.format(gc.getTime()); + gc.add(5, 1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + endtime = format.format(gc.getTime()); + } else { + gc.setTime(dt); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + starttime = format.format(gc.getTime()); + gc.add(5, 1); + gc.set(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), gc.get(Calendar.DATE), 12, 0, 0); + endtime = format.format(gc.getTime()); + } + format = null; + gc = null; + dt = null; + + String strquery = "select control from curdata where terminal='" + terminal + "' and groupid=" + group + + " and control='" + control + "' and " + fieldname + "=1 and wtime>'" + starttime + "' and wtime<='" + + endtime + "' "; + ResultSet rSet = SQLHelper.getResultSet(strquery); + + if (rSet == null) { + return; + } + try { + while (rSet.next()) { + String strsql = "update curdata set " + fieldname + "=1,srcEventId=srcEventId+'(" + eventid + + ")' where control= '" + control + "' and " + fieldname + "=0 and wtime>'" + starttime + + "' and wtime<='" + endtime + "' "; + SQLHelper.ExecSql(strsql); + } + } catch (SQLException e) { + e.printStackTrace(); + } + try { + rSet.close(); + rSet = null; + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * 更新terminals表的eventid字段 + * + * @param terminal + * 终端地址 + * @param eventid + * 主控事件id + */ + public static void updateTerEventId(String terminal, int eventid) { + String strsql = "update terminals set eventid=" + eventid + "' WHERE comid= '" + terminal + "'"; + SQLHelper.ExecSql(strsql); + } + + /** + * 更新MControl表的eventid字段 + * + * @param terminal + * 终端地址 + * @param eventid + * 主控事件id + */ + public static void updateMControlEventId(String terminal, String Comid, int eventid, String time) { + String strsql = "update MControls set eventid=" + eventid + ",mstime='" + time + "' WHERE terminal= '" + + terminal + "' and Comid='" + Comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** + * 更新MControl表的 主控开关状态 交流接触器状态 + * + * @param terminal + * 终端地址 + * @param eventid + * 主控事件id + */ + public static void updateMControlState(String terminal, String Comid, int eventid, int realy1sta, + int ACcontactor1sta, String time) { + String strsql = "update MControls set mstime='" + time + "' ,mstate=" + String.valueOf(realy1sta) + ",mstate1=" + + String.valueOf(realy1sta) + " WHERE terminal= '" + terminal + "' and Comid='" + Comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** 写异常表 */ + public static void wabnormal(String terminal, String content, String remark, String module, String time) { + String strsql = "insert into abnormal (terminal,content,remark,module,wtime)values('" + terminal + "','" + + content + "','" + remark + "','" + module + "','" + time + "')"; + + SQLHelper.ExecSql(strsql); + } + + /** 定采指令写入指令表(commands) */ + public static int wCommands(String terminal, String cmdcode, String comtype, String RuleType) { + String wtime = Common.getDateStr0(); + String strsql = "insert into commands(terminal,cmdcode,Status,WTime, comtype,RuleType,responsetype) values('" + + terminal + "','" + cmdcode + "',0,'" + wtime + "','" + comtype + "','" + RuleType + "','0')"; + return SQLHelper.ExecSql(strsql); + } + + /** 写定采数据表(CurData):抄读路灯状态数据和日冻结灯状态数据 */ + public static void wCurDatanew(String tcomid, int gcomid, String ccomid, int succeed, int stateright, + int arealystate, int brealystate, int wiring, int workmode, int realralaystate, int alamperr, int blamperr, + int ablinkerr, int bblinkerr, int temperatureerr, String readtime, String readstarttime, String batchtime, + String srceventid, String linemode) { + String barcode = businessParameter.getbarcode(ccomid); + String wtime = Common.getDateStr0(); + String strsql = "insert into curdata(barcode,wtime,terminal,groupid,control,succeed, stateright, arealystate, brealystate, wiring, workmode, realralaystate, alamperr, blamperr, ablinkerr, bblinkerr, temperatureerr,readtime,readstarttime,batchtime,srceventid,linemode)values('" + + barcode + "','" + wtime + "','" + tcomid + "','" + gcomid + "','" + ccomid + "','" + succeed + "','" + + stateright + "'," + arealystate + "," + brealystate + "," + wiring + "," + workmode + "," + + realralaystate + "," + alamperr + "," + blamperr + "," + ablinkerr + "," + bblinkerr + "," + + temperatureerr + ",'" + readtime + "','" + readstarttime + "','" + batchtime + "','" + srceventid + + "','" + linemode + "')"; + int result = SQLHelper.ExecSql(strsql); + if (result > 0) { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write data mining operation success"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写定采数据操作成功"); + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write data mining operation failure"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写定采数据操作失败"); + } + } + + /** 写定采数据表(CurData) */ + public static void wCurDataold(String tcomid, int gcomid, String ccomid, int succeed, int lampstate, + int arealystate, int brealystate, int aschedule, int bschedule, int clockstate, int arealyerr, int alamperr, + int ablinkerr, int temperatureerr, int clockerr, String batchtime, String srceventid) { + String barcode = businessParameter.getbarcode(ccomid); + String wtime = Common.getDateStr0(); + String strsql = "insert into curdata(barcode,wtime,terminal,groupid,control,succeed,stateright,arealystate, brealystate, aschedule, bschedule, clockstate, arealyerr, alamperr, ablinkerr, temperatureerr, clockerr,batchtime,readstarttime,srceventid)values('" + + barcode + "','" + wtime + "','" + tcomid + "','" + gcomid + "','" + ccomid + "','" + succeed + "','" + + lampstate + "'," + arealystate + "," + brealystate + "," + aschedule + "," + bschedule + "," + + clockstate + "," + arealyerr + "," + alamperr + "," + ablinkerr + "," + temperatureerr + "," + + clockerr + ",'" + batchtime + "','" + batchtime + "','" + srceventid + "')"; + int result = SQLHelper.ExecSql(strsql); + if (result > 0) { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write data mining operation success"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写定采数据操作成功"); + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write data mining operation failure"); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写定采数据操作失败"); + } + } + + /** 写或更新曲线表 */ + public static void wdatas(String terminal, int pn, String datetime, String field, String value, String batchtime) { + if (!value.equals(null)) { + // 2017-05-20 wwb过滤FF + int i = value.toUpperCase().indexOf("F"); + if (value.toUpperCase().indexOf("F") > -1) { + value = ""; + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->value is FF! " + field + "='" + + value + "';terminal ='" + terminal + "' ; datatime='" + datetime + "' ; no =" + pn); + return; + } + } + int i = 0; + String strsql = "select count(1) count from datas where terminal='" + terminal + "' and datatime='" + datetime + + "' and no=" + pn; + // + " and + // convert(VARCHAR(10),computertime,121)=convert(VARCHAR(10),getdate(),121) + // "; + // 2011-12-16 曲线数据只能数据时间来存储 + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i > 0) {// 更新 + strsql = "update datas set " + field + "='" + value + "' where terminal ='" + terminal + "' and datatime='" + + datetime + "' and no =" + pn; + } else {// 增加 + strsql = "insert into datas (terminal,no,datatime,computertime," + field + ",batchtime) values('" + terminal + + "'," + pn + ",'" + datetime + "','" + wtime + "','" + value + "','" + batchtime + "')"; + // 从meters表更新datas + strsql += "update datas set datas.comid=m.comid from datas, mcontrols m where datas.terminal=m.terminal and datas.no=m.num;"; + } + SQLHelper.ExecSql(strsql); + } + + /** 写或更新曲线表 */ + public void wdatas60(String terminal, int pn, String datetime, String avol, String bvol, String cvol, String acur, + String bcur, String ccur, String Aactpow, String Bactpow, String Cactpow, String actpow, String areactpow, + String breactpow, String creactpow, String reactpow, String aCos, String bCos, String cCos, String AKWh, + String BKWh, String CKWh, String foract, String batchtime) { + + int i = 0; + String strsql = "select count(1) count from datas where terminal='" + terminal + "' and datatime='" + datetime + + "' and no=" + pn; + // + " and + // convert(VARCHAR(10),computertime,121)=convert(VARCHAR(10),getdate(),121) + // "; + // 2011-12-16 曲线数据只能数据时间来存储 + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i > 0) {// 更新 + strsql = "update datas set avol='" + avol + "'," + "bvol='" + bvol + "'," + "ccur ='" + ccur + "'," + + "Aactpow ='" + Aactpow + "'," + "Bactpow ='" + Bactpow + "'," + "Cactpow ='" + Cactpow + "'," + + "actpow ='" + actpow + "'," + "areactpow='" + areactpow + "'," + "breactpow='" + breactpow + + "'," + "creactpow='" + creactpow + "'," + "reactpow ='" + reactpow + "'," + "aCos ='" + aCos + + "'," + "bCos ='" + bCos + "'," + "cCos ='" + cCos + "'," + "AKWh ='" + AKWh + "'," + + "BKWh ='" + BKWh + "'," + "CKWh ='" + CKWh + "'," + "foract ='" + foract + "'" + + " where terminal ='" + terminal + "' and datatime='" + datetime + "' and no =" + pn; + } else {// 增加 + strsql = "insert into datas (terminal,no,datatime,computertime,avol, bvol, cvol, acur, bcur, ccur, Aactpow, Bactpow, Cactpow, actpow, areactpow, breactpow, creactpow, reactpow, aCos, bCos, cCos, AKWh, BKWh, CKWh, foract ,batchtime) values('" + + terminal + "'," + pn + ",'" + datetime + "','" + wtime + "','" + avol + "','" + bvol + "','" + + cvol + "','" + acur + "','" + bcur + "','" + ccur + "','" + Aactpow + "','" + Bactpow + "','" + + Cactpow + "','" + actpow + "','" + areactpow + "','" + breactpow + "','" + creactpow + "','" + + reactpow + "','" + aCos + "','" + bCos + "','" + cCos + "','" + AKWh + "','" + BKWh + "','" + CKWh + + "','" + foract + "','" + batchtime + "');"; + // 从meters表更新datas + strsql += "update datas set datas.comid=m.comid from datas, mcontrols m where datas.terminal=m.terminal and datas.no=m.num" + + " and datas.terminal ='" + terminal + "' and datas.datatime='" + datetime + "';"; + + // 曲线转成日冻结 20190224 每天只保存一次 后续不作更新 + + wMcontroldaydatas(terminal, pn, datetime, foract, datetime, batchtime); + + } + SQLHelper.ExecSql(strsql); + } + + /** + * 写线路开关的日冻结数据 + * + * @param terminal + * 集中器 + * @param McontrolNum + * 主控序号 + * @param fieldtime + * 正向有功的抄读时间 + * @param dataTime + * 数据抄读时间 + * @param batchtime + * 抄读任务批次 + */ + public static void wMcontroldaydatas(String terminal, int McontrolNum, String fieldtime, String value1, + String dataTime, String batchtime) { + String strsql = "select count(1) count from daydatas where terminal='" + terminal + "' and no=" + McontrolNum + + " and substring(datadate,1,10)=substring('" + dataTime + "',1,10) and types='0004'"; + int i = 0; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i == 0) {// 增加 + + strsql = "insert into daydatas (terminal,no,foracttime,datadate,computertime,succeed,types,foract) " + + "values('" + terminal + "' ," + McontrolNum + ",'" + fieldtime + "','" + dataTime.substring(0, 10) + + "','" + wtime + "','1','0004','" + value1 + "');"; + // 从meters表更新daydatas + // strsql += "update daydatas set daydatas.circuitry=(SELECT TOP 1 + // line FROM terminals WHERE + // terminals.comid=daydatas.terminal),daydatas.comid=m.comid,daydatas.digit=6,daydatas.types='0006' + // from daydatas, controls m where daydatas.terminal=m.terminal and + // daydatas.no=m.num AND daydatas.types IS null;"; + strsql += "update daydatas set daydatas.comid=m.comid,daydatas.digit=6,daydatas.multiple=m.multiple from daydatas, " + + " Mcontrols m where daydatas.terminal=m.terminal and daydatas.no=m.num AND daydatas.multiple IS null and daydatas.types='0004';"; + + SQLHelper.ExecSql(strsql); + // 更新表记电量 没有计算过周 + strsql = "update daydatas set happen= isnull((cast(foract as decimal(12,2))-(SELECT max(cast(foract as decimal(12,2))) FROM daydatas " + + " WHERE foracttime 0) + strsql = "update datas set Aactpow='" + dataStrings[0] + "'," + "Bactpow='" + dataStrings[1] + "'," + + "Cactpow='" + dataStrings[2] + "' " + " where terminal ='" + terminal + "' and datatime='" + + datetime + "' "; + else + strsql = "insert into datas(terminal,no,datatime,computertime,Aactpow,Bactpow,Cactpow,batchtime) " + + "values('" + terminal + "'," + pn + ",'" + datetime + "','" + wtime + "'," + "'" + + dataStrings[0] + "','" + dataStrings[1] + "','" + dataStrings[2] + "','" + batchtime + "')"; + break; + case 31:// 昨天总功率因数/三相功率因数 + if (i > 0) + strsql = "update datas set Cos='" + dataStrings[0] + "'," + "aCos='" + dataStrings[1] + "'," + "bCos='" + + dataStrings[2] + "'," + "cCos='" + dataStrings[3] + "' " + " where terminal ='" + terminal + + "' and datatime='" + datetime + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,Cos,aCos,bCos,cCos,batchtime) " + + "values('" + terminal + "'," + pn + ",'" + datetime + "','" + wtime + "'," + "'" + + dataStrings[0] + "','" + dataStrings[1] + "','" + dataStrings[2] + "','" + dataStrings[3] + + "','" + batchtime + "')"; + break; + case 33:// 昨天总有功功率 + if (i > 0) + strsql = "update datas set actpow ='" + dataStrings[0] + "' where terminal ='" + terminal + + "' and datatime='" + datetime + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,actpow,batchtime) values('" + terminal + + "'," + pn + ",'" + datetime + "','" + wtime + "','" + dataStrings[0] + "','" + batchtime + + "')"; + break; + + case 35:// 昨天三相电压 + if (i > 0) + strsql = "update datas set avol='" + dataStrings[0] + "'," + "bvol='" + dataStrings[1] + "'," + "cvol='" + + dataStrings[2] + "' " + " where terminal ='" + terminal + "' and datatime='" + datetime + + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,avol,bvol,cvol,batchtime) " + "values('" + + terminal + "'," + pn + ",'" + datetime + "','" + wtime + "'," + "'" + dataStrings[0] + "','" + + dataStrings[1] + "','" + dataStrings[2] + "','" + batchtime + "')"; + break; + case 38:// 昨天三相电流 + if (i > 0) + strsql = "update datas set acur='" + dataStrings[0] + "'," + "bcur='" + dataStrings[1] + "'," + "ccur='" + + dataStrings[2] + "' " + " where terminal ='" + terminal + "' and datatime='" + datetime + + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,acur,bcur,ccur,batchtime) " + "values('" + + terminal + "'," + pn + ",'" + datetime + "','" + wtime + "'," + "'" + dataStrings[0] + "','" + + dataStrings[1] + "','" + dataStrings[2] + "','" + batchtime + "')"; + break; + case 41:// 昨日正向有功电能量 + if (dataCount == 0) // 写日冻结数据 由于路灯没有日冻结数据,所以只能使用曲线的0点数据作库日冻结数据 + { + String YessterdayString = Common.getYesterdayStr7(); + String nowString = Common.getDateStr0(); + int rowCount = 0; + strsql = "select count(terminal) num from daydatas where terminal='" + terminal + "' and datadate='" + + YessterdayString + "' and types='0002'"; + rSet = SQLHelper.getResultSet(strsql); + if (rSet != null) { + try { + while (rSet.next()) { + rowCount = rSet.getInt("num"); + } + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + if (rowCount == 0) { + // 获取集中器信息 + String line = ""; + int multiple = 1; + int digit = 6; + String types = "0002"; + strsql = "select multiple,line from terminals where comid='" + terminal + "'"; + rSet = SQLHelper.getResultSet(strsql); + if (rSet != null) { + try { + while (rSet.next()) { + line = rSet.getString("line"); + multiple = rSet.getInt("multiple"); + } + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + strsql = "insert into daydatas(circuitry,terminal,multiple,digit,types,foract,Computertime,foracttime,datadate,succeed,comid)" + + " values(" + "'" + line + "'," + "'" + terminal + "'," + String.valueOf(multiple) + "," + + String.valueOf(digit) + "," + "'" + types + "'," + "'" + dataStrings[0] + "'," + "'" + + nowString + "'," + "'" + YessterdayString + " 00:00:00" + "'," + "'" + YessterdayString + + "'," + "'1'," + "'" + terminal + "'" + ")"; + SQLHelper.ExecSql(strsql); + // 计算发生电量 没有过周的计算 + strsql = "update daydatas set happen= " + " isnull(" + + " (cast(foract as NUMERIC(10,2))-(SELECT top 1 (cast(foract as NUMERIC(10,2))) " + + " FROM daydatas WHERE foracttime 0) + strsql = "update datas set foract ='" + dataStrings[0] + "' where terminal ='" + terminal + + "' and datatime='" + datetime + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,foract,batchtime) values('" + terminal + + "'," + pn + ",'" + datetime + "','" + wtime + "','" + dataStrings[0] + "','" + batchtime + + "')"; + break; + case 43:// 昨天PM2.5 + if (i > 0) + strsql = "update datas set pm25 ='" + dataStrings[0] + "' where terminal ='" + terminal + + "' and datatime='" + datetime + "' "; + else + strsql = "insert into datas (terminal,no,datatime,computertime,pm25,batchtime) values('" + terminal + + "'," + pn + ",'" + datetime + "','" + wtime + "','" + dataStrings[0] + "','" + batchtime + + "')"; + break; + default: + break; + } + + if (false) // i == 0 + // 从meters表更新datas + strsql += "update datas set datas.comid=m.comid,datas.meterid=m.meterid from datas, meters m where datas.terminal=m.terminal and datas.no=m.no;"; + + SQLHelper.ExecSql(strsql); + } + + /** 写或更新日冻结数据表 rtime 终端抄读时间 正向与反抄读时间可能会不一 日冻结数据没有日期字段 */ + public static void wdaydatas(String terminal, int multiple, int pn, String fieldtime, String time, String field1, + String field2, String field3, String field4, String field5, String value1, String value2, String value3, + String value4, String value5) { + // and + // convert(VARCHAR(10),computertime,121)=convert(VARCHAR(10),getdate(),121) + // 这个条件还是多余的 + int i = 0; + String strsql = "select count(1) count from daydatas where terminal='" + terminal + "' and no=" + pn + + " and substring(datadate,1,10)=substring('" + time + "',1,10) "; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + + String wtime = Common.getDateStr0(); + if (i > 0) {// 更新 + strsql = "update daydatas set multiple =" + multiple + "," + fieldtime + "='" + time + "'," + field1 + "='" + + value1 + "'," + field2 + "='" + value2 + "'," + field3 + "='" + value3 + "'," + field4 + "='" + + value4 + "'," + field5 + "='" + value5 + "' where terminal ='" + terminal + + "' and substring(datadate,1,10)=substring('" + time + "',1,10) and no=" + pn; + } else {// 增加 + strsql = "insert into daydatas (terminal,multiple,no," + fieldtime + ",datadate,computertime,succeed," + + field1 + "," + field2 + "," + field3 + "," + field4 + "," + field5 + ",types) values('" + terminal + + "'," + multiple + "," + pn + ",'" + time + "','" + time.substring(0, 10) + "','" + wtime + + "','1','" + value1 + "','" + value2 + "','" + value3 + "','" + value4 + "','" + value5 + + "','0003');"; + // 从meters表更新daydatas + // strsql += "update daydatas set daydatas.circuitry=(SELECT TOP 1 + // line FROM terminals WHERE + // terminals.comid=daydatas.terminal),daydatas.comid=m.comid,daydatas.digit=6,daydatas.types='0006' + // from daydatas, controls m where daydatas.terminal=m.terminal and + // daydatas.no=m.num AND daydatas.types IS null;"; + strsql += "update daydatas set daydatas.comid=m.comid,daydatas.digit=6 from daydatas, " + + "controls m where daydatas.terminal=m.terminal and daydatas.no=m.num AND daydatas.comid IS null and daydatas.types='0003';"; + } + SQLHelper.ExecSql(strsql); + // 更新表记电量 没有计算过周 + strsql = "update daydatas set happen= isnull((cast(foract as decimal(12,2))-(SELECT max(cast(foract as decimal(12,2))) FROM daydatas " + + " WHERE foracttime 0) {// 更新 + strsql = "update daydatas set multiple =" + rates + "," + fieldtime + "='" + time + "'," + field1 + "='" + + value1 + "'," + field2 + "='" + value2 + "'," + field3 + "='" + value3 + "'," + field4 + "='" + + value4 + "'," + field5 + "='" + value5 + "' where terminal ='" + terminal + + "' and substring(datadate,1,10)=substring('" + time + "',1,10) and no=" + pn; + } else {// 增加 + strsql = "insert into daydatas (terminal,multiple,no," + fieldtime + ",datadate,computertime,succeed," + + field1 + "," + field2 + "," + field3 + "," + field4 + "," + field5 + ") values('" + terminal + + "'," + rates + "," + pn + ",'" + time + "','" + time.substring(0, 10) + "','" + wtime + "','1','" + + value1 + "','" + value2 + "','" + value3 + "','" + value4 + "','" + value5 + "');"; + // 从meters表更新daydatas + // strsql += "update daydatas set + // daydatas.userid=m.recordid,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.comid=m.comid,daydatas.meter=m.meterid,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types + // from daydatas, meters m where daydatas.terminal=m.terminal and + // daydatas.no=m.no;"; + strsql += "update daydatas set daydatas.userid=m.recordid,daydatas.circuitry=m.line,daydatas.transformer=m.transformer,daydatas.comid=m.comid,daydatas.meter=m.meterid,daydatas.meterid=m.meterid,daydatas.digit=m.digit,daydatas.types=m.types " + + "from daydatas, meters m where daydatas.terminal=m.terminal and daydatas.no=m.no;"; + } + SQLHelper.ExecSql(strsql); + // 更新表记电量 + strsql = "update daydatas set happen= isnull((cast(foract as numeric)-(SELECT max(cast(foract as numeric)) FROM daydatas WHERE foracttime 0) { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write the event table operation is successful:" + wdata); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写事件表操作成功:" + wdata); + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + + "->Write the event table operation failed:" + wdata); + else + Log.writelog(Protocol.clazzName, + Thread.currentThread().getStackTrace()[1].getMethodName() + "->写事件表操作失败:" + wdata); + } + } + + /** 写主控状态变化事件表(mControlEvent) */ + + public static void wmControlEvent(String barcode, String comid, String terminal, String wtime, int realyrunmode, + int schedulerunmode, int realy1sta, int ACcontactor1sta, int timing, int erccode, int eventid) { + String strsql = "insert into mcontrolEvent(barcode,comid,terminal,wtime,realyrunmode, " + + "schedulerunmode, " + "realy1sta, " + "ACcontactor1sta, " + + " timing, erccode,eventid )values('" + barcode + "','" + comid + "','" + terminal + "','" + + wtime + "'," + realyrunmode + "," + schedulerunmode + "," + realy1sta + "," + ACcontactor1sta + + + "," + timing + "," + erccode + "," + eventid + ")"; + int result = SQLHelper.ExecSql(strsql); + if (result > 0) { + // 更新terminal表的eventid字段 + if (erccode == 42)// 故障时 + updateMControlEventId(terminal, comid, eventid, wtime); // eventid + // 如何获取 + else + updateMControlState(terminal, comid, eventid, realy1sta, ACcontactor1sta, wtime);// 更新回路控制器的状态 + + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Write the master table operation successful state change events"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]写主控状态变化事件表操作成功"); + + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Write master state change event table operation failed"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]写主控状态变化事件表操作失败"); + } + } + + public static void wmControlEvent(String barcode, String comid, String terminal, String wtime, int realyrunmode, + int schedulerunmode, int realy1sta, int ACcontactor1sta, int programsta, int volitagesta, int controlsta, + int commchannel, int scheduleinmonth, int scheduleinholiday, int scheduleinspring, int onoffinput, + int timing, int control, int realy1err, int ACcontactor1err, int erccode, int eventid) { + String strsql = "insert into mcontrolEvent(barcode,comid,terminal,wtime,realyrunmode, " + + "schedulerunmode, " + "realy1sta, " + + "ACcontactor1sta, programsta, volitagesta, controlsta, commchannel," + + " scheduleinmonth, scheduleinholiday, scheduleinspring, onoffinput," + + " timing, control, realy1err, ACcontactor1err, erccode,eventid )values('" + barcode + "','" + + comid + "','" + terminal + "','" + wtime + "'," + realyrunmode + "," + schedulerunmode + "," + + realy1sta + "," + ACcontactor1sta + "," + programsta + "," + volitagesta + "," + controlsta + "," + + commchannel + "," + scheduleinmonth + "," + scheduleinholiday + "," + scheduleinspring + "," + + onoffinput + "," + timing + "," + control + "," + realy1err + "," + ACcontactor1err + "," + erccode + + "," + eventid + ")"; + int result = SQLHelper.ExecSql(strsql); + if (result > 0) { + // 更新terminal表的eventid字段 + updateMControlEventId(terminal, comid, eventid, wtime); + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Write the master table operation successful state change events"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]写主控状态变化事件表操作成功"); + + } else { + if (language.equals("en")) + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]Write master state change event table operation failed"); + else + Log.writelog(Protocol.clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + + terminal + "]写主控状态变化事件表操作失败"); + } + } + + /** 写入结果表(ReceiveData) */ + public void wReceiveData(int cmdid, String terminal, String cmdcode, int state) { + String remark = ""; + switch (state) { + case 1: + remark = "NOT ONLINE"; + break; + case 2: + remark = "BUSY"; + break; + case 3: + remark = "TimeOUT"; + break; + case 4: + remark = "GPRS server connection failure"; + break; + } + if (cmdcode.endsWith("-")) { + cmdcode = cmdcode.substring(0, cmdcode.length() - 1); + } + int result = SQLHelper.ExecProcwreceivedata(cmdid, terminal, cmdcode, state, remark); + + if (remark.equals("")) { + if (result == 1) { + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]Write the results table operation is successful:" + cmdcode); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]写结果表操作成功:" + cmdcode); + } else { + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]Write the results table operation failed:" + cmdcode); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]写结果表操作失败:" + cmdcode); + + } + } else { + if (language.equals("en")) + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]Write the results:" + remark); + else + Log.writelog(clazzName, Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + terminal + + "]写结果状态:" + remark); + } + } + + public static void upatetempmeters(String runtime, String taskidString) { + String strsql = "update tempmeters set runtime='" + runtime + "',count=0 where id=" + taskidString; + SQLHelper.ExecSql(strsql); + } + + public static void updateTerminalsLuxState(String comid) { + String strsql = "update terminals set luxstate=1 where comid='" + comid + "'"; + SQLHelper.ExecSql(strsql); + } + + /** + * 写电表补抄记录 + * + * @param terminal + * 集中器通信地址l + * @param afncode + * DA+DT+参数 + * @param comtype + * 通道类型 + * @param no + * 测量点号 + * @param td + * 数据时间参数 生成时间 + * @param intervalTiming + * 补抄间隔 + */ + public static void wtempmeters(String terminal, String afncode, String comtype, int no, String td, + int intervalTiming) { + int i = 0; + // td = td.replace("-", ""); //2011-11-26 wwb 防止'01-11-11'格式的写入 + if (afncode == null || afncode.equals("")) // 2011-12-24 wwb + // 防止非定采任务写到补抄表中 + return; + String strsql = "select count(1) count from tempmeters where terminal='" + terminal + "' and no=" + no + + " and code='" + afncode + "' "; + java.sql.Statement stmt = null; + ResultSet rSet = SQLHelper.getResultSet(strsql); + if (rSet == null) { + return; + } + try { + rSet.next(); + i = rSet.getInt("count"); + } catch (Exception e) { + e.printStackTrace(); + } + try { + stmt = rSet.getStatement(); + rSet.close(); + stmt.close(); + rSet = null; + stmt = null; + } catch (Exception e) { + e.printStackTrace(); + } + // 更新下一次运行时间,以及补抄运行次数 + String runTime = Common.getDateStr0(); + if (i == 0) { + strsql = "insert into tempmeters(terminal,code,no,commodel,td,count,intervalTiming,runTime,wtime,protocol) values('" + + terminal + "','" + afncode + "'," + no + ",'" + comtype + "','" + td + "',0," + + String.valueOf(intervalTiming) + "" + ",'" + runTime + "','" + td + "','0002')"; + SQLHelper.ExecSql(strsql); + } + + } + + /** + * 抄读成功后,删除相应补抄记录 + * + * @param terminal + * 集中器通信地址 + * @param afncode + * 功能码 "od:11" + * @param pn + * 测量点号 + * @param td + * 数据时标 任务生成时间 + */ + public static void deltempmeters(String terminal, String afncode, int pn, String td) { + String strsql = "delete from tempmeters where terminal='" + terminal + "' and code='" + afncode + "' and no=" + + pn + " and td='" + td + "'"; + // Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + // + "->[" + // +terminal +"]删除临时表:" + strsql); + SQLHelper.ExecSql(strsql); + } + + /** + * 抄读成功后,删除相应补抄记录 + * + * 数据时标 任务生成时间 + * + * @param taskidString + */ + public static void deltempmeters(String taskidString) { + String strsql = "delete from tempmeters where id=" + taskidString; + // Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + // + "->[" + // +terminal +"]删除临时表:" + strsql); + SQLHelper.ExecSql(strsql); + + } + +} \ No newline at end of file diff --git a/selfDevelop/src/main/java/com/back/sync/DataInstance.java b/selfDevelop/src/main/java/com/back/sync/DataInstance.java new file mode 100644 index 0000000..20c1291 --- /dev/null +++ b/selfDevelop/src/main/java/com/back/sync/DataInstance.java @@ -0,0 +1,95 @@ +package com.back.sync; + +import java.util.List; + +import com.back.entity.Control; +import com.back.entity.Mcontrol; +import com.back.entity.Sensor; + +public class DataInstance { + + public static DataInstance dataInstance = null; + + public static DataInstance getInstance() { + if (dataInstance == null) { + dataInstance = new DataInstance(); + } + return dataInstance; + } + + public static void resetInstance() { + dataInstance = null; + } + + private List controlList; + private List mcontrolList; + // 照度 + private List illumList; + // 亮度 + private List lumList; + // 车流量 + private List carsenList; + + private int totalCount; + private int syncedCount; + private int progress; + + // 命令发送状态 + private int state; + + public List getControlList() { + return controlList; + } + public void setControlList(List controlList) { + this.controlList = controlList; + } + public List getMcontrolList() { + return mcontrolList; + } + public void setMcontrolList(List mcontrolList) { + this.mcontrolList = mcontrolList; + } + public List getIllumList() { + return illumList; + } + public void setIllumList(List illumList) { + this.illumList = illumList; + } + public List getLumList() { + return lumList; + } + public void setLumList(List lumList) { + this.lumList = lumList; + } + public List getCarsenList() { + return carsenList; + } + public void setCarsenList(List carsenList) { + this.carsenList = carsenList; + } + public int getTotalCount() { + return totalCount; + } + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + public int getSyncedCount() { + return syncedCount; + } + public void setSyncedCount(int syncedCount) { + this.syncedCount = syncedCount; + } + public int getProgress() { + return progress; + } + public void setProgress(int progress) { + this.progress = progress; + } + public int getState() { + return state; + } + public void setState(int state) { + this.state = state; + } + +} diff --git a/selfDevelop/src/main/java/com/back/sync/DataSyncUtil.java b/selfDevelop/src/main/java/com/back/sync/DataSyncUtil.java new file mode 100644 index 0000000..dcdb28a --- /dev/null +++ b/selfDevelop/src/main/java/com/back/sync/DataSyncUtil.java @@ -0,0 +1,666 @@ +package com.back.sync; + +import java.text.SimpleDateFormat; +import java.util.List; + +import com.back.action.Log; +import com.back.common.Common; +import com.back.entity.Control; +import com.back.entity.Mcontrol; +import com.back.entity.Sensor; +import com.back.protocol.GW3761; + +public class DataSyncUtil { + + /** + * 获取设置命令 datas 具体设置的报文 terminal 集中器通信地址 + */ + private static class Cmdinfor { + String afn; // AFN + String Comid; // 通信地址 + String datas; // 数据区内容 + Boolean FCV; // 帧计数有效位FCV + String FCB; // FCB + String host; // 主站地址 + String PWD; // 密码 + int PFC; // PFC + Boolean bTime; // 是否有时间标签 + int outTime;// 允许发送传输延时时间 + Boolean TP;// 是否有时间标签 + Boolean CON;// CON位置“true”,表示需要对该帧报文进行确认;置“false”,表示不需要对该帧报文进行确认。 + + public void Create(String afn, String comid, String datas, int PFC, Boolean btime) { + datas = datas.replace(" ", ""); + datas = datas.trim(); + this.afn = afn; + while (comid.length() < 8) + comid = "0" + comid; + this.Comid = comid; + this.datas = datas; + this.FCV = false; + this.PFC = PFC; + this.FCB = "01"; + this.host = "02"; + this.PWD = "00000000000000000000000000000000";// 固定密码 16个零 + this.bTime = btime; + this.outTime = 5; + this.TP = btime; + this.CON = true; + } + } + + private static Cmdinfor cmdinfor = new Cmdinfor(); + + /** + * 配置灯具下发数据 202101 + * + * @param + * + * @param flag + * true为新增,false为删除 + * @return + */ + public static String configLampData(List controlList, boolean flag) { + String data = "", temp = ""; + try { + for (int i = 0; i < controlList.size(); i++) { + Control control = controlList.get(i); + + // 灯装置序号(2个字节) + temp = dec2Hex(control.getNum(), 4); + data = data + " " + temp.substring(2, 4); + data = data + " " + temp.substring(0, 2); + + // 测量点号(2个字节) + // if (flag) { + // data = data + " " + temp.substring(2, 4); + // data = data + " " + temp.substring(0, 2); + // } else { + // data += " 00 00"; + // } + + // 灯通信地址(6个字节) + temp = control.getComid(); + temp = "000000000000" + temp; + temp = temp.substring(temp.length() - 12); + for (int j = temp.length(); j > 0; j -= 2) { + data += " " + temp.substring(j - 2, j); + } + + // 通讯信道(1个字节),即通信端口 + // 1-载波通信 2-RS485_1口通信 3-RS485_2口通信 4-LORA无线通信(5-255:备用) + String tunnel = control.getTunnel(); + data += " " + tunnel.substring(2, 4); + + // 通信协议(1个字节) + // 1-DL645_97版 2-DL645_07版 3-ModBus协议 (4-255:备用) + String protocol = control.getProtocol(); + data += " " + protocol.substring(2, 4); + + // 所属组号(1个字节) + data = data + " " + dec2Hex(control.getGroupid(), 2); + + // 工作方式(1个字节) + String worktypeString = control.getWorktype(); + // 00 时间表;01经纬度;02 场景模式 + data += " " + worktypeString.substring(2, 4); + + // 灯杆类型(1个字节) + // 1—单灯调光 2-双色温调光 3-双灯头调光(3-255:备用) + String type = control.getType(); + data += " " + type.substring(2, 4); + + } + } catch (Exception e) { + Log.writelog1("构造灯杆安装命令出错, error:" + e.getMessage()); + e.printStackTrace(); + } + return data; + } + + public static String SendCmd(int type, int count, String message) { + int[] cmd = new int[3]; + cmd[0] = 0x81; + cmd[1] = 0x01; + cmd[2] = type; + + StringBuilder builder = new StringBuilder(); + for (int i = 1; i < cmd.length; i++) { + builder.append(" " + dec2Hex(cmd[i], 1)); + } + + return builder.toString(); + } + + public static String preSendCmd(String terminal) { + + String cmdCode = "0000" + GW3761.GetDAOrDT(4, 1) + "81" + "01" + "00"; + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = terminal.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + return gw3761.create3761("64", adomain, "FD", seqdomain, cmdCode); + } + + public static String genetateLampData(String terminal, List controlList) { + String data = configLampData(controlList, Boolean.TRUE); +// String temp = dec2Hex(controlList.size(), 4); +// String msgString = temp.substring(2, 4) + " " + temp.substring(0, 2) + " " + data; +// msgString = GetDAOrDT(21, 1) + msgString.trim(); +// cmdinfor.Create("A4", terminal, msgString, GetPFC(), false); + + String cmdCode = "0000" + GW3761.GetDAOrDT(4, 1) + + "81" + "02" + "01" + dec2Hex(controlList.size(), 2) + data; + cmdCode = cmdCode.replace(" ", ""); + + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = terminal.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + return gw3761.create3761("64", adomain, "FD", seqdomain, cmdCode); + } + + private static GW3761 gw3761 = new GW3761(); // 新集中器解码类 + private static int PFC = 0; // 启动帧帧序号计数器(0~255) + + public static String generateMcontrolData(String terminal, List mcontrolList) { + String message = configMcontrolData(mcontrolList, Boolean.TRUE); +// message = GetDAOrDT(36, 1) + message; +// cmdinfor.Create("A4", terminal, message, GetPFC(), false); + String cmdCode = "0000" + GW3761.GetDAOrDT(4, 1) + + "81" + "02" + "02" + dec2Hex(mcontrolList.size(), 2) + message; + cmdCode = cmdCode.replace(" ", ""); + + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = terminal.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + return gw3761.create3761("64", adomain, "FD", seqdomain, cmdCode); + } + + public static String generateSensorData(String terminal, List sensorList, int fn, String sensorType) { + String message = configSensorData(sensorList, Boolean.TRUE); +// String temp = dec2Hex(1, 2); +// message = temp.substring(0, 2) + " " + message; +// message = GetDAOrDT(fn, 1) + message.trim(); +// cmdinfor.Create("A4", terminal, message, GetPFC(), false); +// return GetSendCmd(cmdinfor); + String cmdCode = "0000" + GW3761.GetDAOrDT(4, 1) + + "81" + "02" + sensorType + dec2Hex(sensorList.size(), 2) + message; + cmdCode = cmdCode.replace(" ", ""); + + String binarypfc = "00000000" + Common.inttobinary(PFC); + PFC++; + if (PFC == 255) + PFC = 0; + + binarypfc = Common.right(binarypfc, 4); + String seqdomain = Common.binarytohex("0111" + binarypfc); + char[] chars = terminal.toCharArray(); + String adomain = String.valueOf(chars[2]) + String.valueOf(chars[3]) + String.valueOf(chars[0]) + + String.valueOf(chars[1]) + String.valueOf(chars[6]) + String.valueOf(chars[7]) + + String.valueOf(chars[4]) + String.valueOf(chars[5]) + "04"; + return gw3761.create3761("64", adomain, "FD", seqdomain, cmdCode); + } + + public static String configMcontrolData(List mcontrolList, boolean flag) { + String data = "", temp = ""; + try { + for (int i = 0; i < mcontrolList.size(); i++) { + Mcontrol mcontrol = mcontrolList.get(i); + + // 主控装置序号(2个字节) + temp = dec2Hex(mcontrol.getNum(), 4); + data = data + temp.substring(2, 4) + " " + temp.substring(0, 2); + + // 测量点号(2个字节) + // if (flag) { + // data += " " + temp.substring(2, 4) + " " + temp.substring(0, + // 2); + // } else { + // data += " 00 00"; + // } + + // 通信地址(6个字节) + temp = mcontrol.getComid(); + while (temp.length() < 12) + temp = "0" + temp; + for (int j = temp.length(); j > 0; j -= 2) { + data += " " + temp.substring(j - 2, j); + } + + // 通讯信道(1个字节):1为载波口 2为第一个485口 3为第二个485口 + temp = mcontrol.getTunnel(); + data += " " + temp.substring(2, 4); + + // 通讯协议(1个字节):1-DL645_97版 2-DL645_07版 3-ModBus协议 (4-255:备用) + temp = mcontrol.getProtocol(); + data += " " + temp.substring(2, 4); + + // 该线路所属组号(1个字节) + if (mcontrol.getGroups() == null) { + temp = ""; + } else { + temp = mcontrol.getGroups().trim(); + } + + if (temp.equals("")) { + data += " 00"; + } else { + temp = dec2Hex(Integer.parseInt(temp), 2); + data += " " + temp; + } + + // 工作方式(1个字节) + String worktypeString = mcontrol.getWorktype(); + if (worktypeString.equals("0001")) { // 走经纬度 + data += " 01"; + } else if (worktypeString.equals("0000")) { // 走时间表 + data += " 00"; + } else if (worktypeString.equals("0002")) { // 场景模式 + data += " 02"; + } + + // 回路类型(1个字节) + temp = dec2Hex(mcontrol.getType(), 2); + data += " " + temp; + + // 回路电流互感器变比值(1个字节) + temp = dec2Hex(mcontrol.getRatio(), 2); + data += " " + temp; + } + } catch (Exception e) { + Log.writelog1("构造回路安装命令出错, error:" + e.getMessage()); + e.printStackTrace(); + } + return data; + } + + public static String configSensorData(List sensorList, boolean flag) { + String data = "", temp = ""; + try { + for (int i = 0; i < sensorList.size(); i++) { + Sensor sensor = sensorList.get(i); + + // 灯装置序号(2个字节) + temp = dec2Hex(sensor.getNum(), 4); + data = data + " " + temp.substring(2, 4); + data = data + " " + temp.substring(0, 2); + + // 测量点号(2个字节) + // if (flag) { + // data = data + " " + temp.substring(2, 4); + // data = data + " " + temp.substring(0, 2); + // } else { + // data += " 00 00"; + // } + + // 灯通信地址(6个字节) + temp = sensor.getComid(); + temp = "000000000000" + temp; + temp = temp.substring(temp.length() - 12); + for (int j = temp.length(); j > 0; j -= 2) { + data += " " + temp.substring(j - 2, j); + } + + // 通讯信道(1个字节),即通信端口 1-载波通信 2-RS485_1口通信 3-RS485_2口通信 + // 4-LORA无线通信(5-255:备用) + String tunnel = sensor.getTunnel(); + data += " " + tunnel.substring(2, 4); + + // 通信协议(1个字节) 1-DL645_97版 2-DL645_07版 3-ModBus协议 (4-255:备用) + String protocol = sensor.getProtocol(); + data += " " + protocol.substring(2, 4); + + int fn = 0; + if (sensor.getType().equals("0001")) {// 照度传感器 + fn = 37; + } else if (sensor.getType().equals("0002")) {// 亮度传感器 + fn = 38; + // 转换系数(1个字节) + temp = dec2Hex(sensor.getRatio(), 2); + data += " " + temp; + } else if (sensor.getType().equals("0003")) {// 车流量传感器 + fn = 39; + // 车流量统计周期(1个字节) + temp = dec2Hex(sensor.getCycle(), 2); + data += " " + temp; + // 车道数量(1个字节) + temp = dec2Hex(sensor.getLane(), 2); + data += " " + temp; + } + + } + + } catch (Exception e) { + Log.writelog1("构造传感器安装命令出错, error:" + e.getMessage()); + e.printStackTrace(); + } + return data; + } + + /** + * 10进制转16进制 + * + * @param dec + * 要转换的数值 + * @param len + * 16进制的长度 + * @return + */ + private static String dec2Hex(int dec, int len) { + String tempString = Integer.toHexString(dec); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + + /** + * 10进制字符串转16进制字符串 + * + * @param dec + * @return + */ + public static String dec2Hex(String dec, int len) { + if (dec == null || dec.equals("")) + dec = "0"; + String tempString = Long.toHexString(Long.parseLong(dec)); + while (tempString.length() < len) { + tempString = "0" + tempString; + } + return tempString.trim(); + } + + /** + * 为0时计算信息点标识DA(Pn),为1计算信息类标识DT(Fn) + * + * @param value + * @param flag + * 0/1 + * @return F30,返回值格式:00 00 20 03 + */ + public static String GetDAOrDT(int value, int flag) { + int d = 0; + String D1, D2 = "0"; + + if (value == 0) { + D1 = "0"; + D2 = "0"; + } else { + d = value % 8; + + if (d == 0) { + D1 = "1" + repeat(7, '0'); + d = value / 8 - 1; + if (flag == 0) { + d = d + 1; + } + } else { + D1 = "1" + repeat(d - 1, '0'); + d = value / 8; + if (flag == 0) { + d = d + 1; + } + } + } + + D1 = Common.right("00" + Common.binarytohex(D1), 2); + D2 = Common.right("00" + Common.inttohex(d), 2); + return "00 00 " + D1 + " " + D2; + } + + /** 返回指定字符的重复 */ + public static String repeat(int len, char c) { + StringBuffer sbf = new StringBuffer(); + int i = 0; + while (i < len) { + i += 1; + sbf.append(c); + } + return sbf.toString(); + } + + private static int GetPFC() { + return 1; + } + + private static int msg[] = new int[2024]; + + private static String GetSendCmd(Cmdinfor cmdinfor) { + int count = cmdinfor.datas.length(); + int i; + String temp; + for (i = 0; i < msg.length; i++) + msg[i] = 0; + + // 报文头 + msg[0] = 0x68;// 68H + msg[5] = 0x68;// 68H + // 控制码 + msg[6] = GetDownCortrolByte(cmdinfor.afn, cmdinfor.FCB, cmdinfor.FCV);// C + // 控制位 + // 通信地址 16进制字 + temp = cmdinfor.Comid.substring(0, 4); + msg[8] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + msg[7] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A1 + // 2字节 BCD码 + temp = cmdinfor.Comid.substring(4); + msg[10] = Integer.parseInt(temp.substring(0, 2), 16) & 0xFF; // A 地址域 + // --> + // 行政区划码 + // A2 + // 2字节 + // BCD码 + msg[9] = Integer.parseInt(temp.substring(2), 16) & 0xFF; // A 地址域 --> + // 行政区划码 A2 + // 2字节 BCD码 + // 主站地址 + msg[11] = (Integer.parseInt(cmdinfor.host, 16) << 1) & 0xFF;// A 地址域 --> + // 主站地址 A3 + // 1字节 Bin码 + msg[12] = Integer.parseInt(cmdinfor.afn, 16) & 0xFF; // AFN + if (cmdinfor.bTime) + temp = "111"; + else + temp = "011"; + // 20190216 增加 请求确认标志位 + if (cmdinfor.CON) + temp = temp + "1"; + else + temp = temp + "0"; + msg[13] = (binaryString2Int(temp) << 4) + (cmdinfor.PFC % 16); // SEQ + // 帧序列域 + int len = cmdinfor.datas.length() / 2; + for (int j = 0; j < (len); j++) { + temp = cmdinfor.datas.substring(j * 2, (j * 2 + 2)); + msg[14 + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 13; + if (CheckDwnPw(cmdinfor.afn)) { + len++; + for (int j = 0; j < 16; j++) { // 密码 + temp = cmdinfor.PWD.substring(j * 2, (j * 2 + 2)); + msg[len + j] = Integer.parseInt(temp, 16) & 0xFF; + } + len = len + 15; + } + + if (cmdinfor.TP) { + SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String datetime = tempDate.format(new java.util.Date()); + len++; + msg[len] = cmdinfor.PFC;// 启动帧帧序号计数器PFC + len++; + msg[len] = Integer.parseInt(datetime.substring(17, 19), 16);// 启动帧发送时标 + // 秒 + len++; + msg[len] = Integer.parseInt(datetime.substring(14, 16), 16);// 启动帧发送时标 + // 分 + len++; + msg[len] = Integer.parseInt(datetime.substring(11, 13), 16);// 启动帧发送时标 + // 时 + len++; + msg[len] = Integer.parseInt(datetime.substring(8, 10), 16);// 启动帧发送时标 + // 日 + len++; + msg[len] = 1;// 允许发送传输延时时间 + } + len++; + msg[len] = GetCS(len); + len++; + msg[len] = 0x16; + count = len - 7; + count = (count << 2) + 2; + msg[1] = count % 0x100; + msg[2] = count / 0x100; + msg[3] = count % 0x100; + msg[4] = count / 0x100; + + // 转成字符串 + StringBuffer sendBuffer = new StringBuffer(); + for (int j = 0; j <= len; j++) + sendBuffer.append(" " + dec2Hex(msg[j], 2)); + + System.out.println(sendBuffer.toString().trim()); + return sendBuffer.toString().trim(); + } + + /** + * 获取相应的功能码 + * + * @param sType + * @param sFCB + * @param bFCV + * @return + */ + private static Integer GetDownCortrolByte(String sType, String sFCB, Boolean bFCV) { + String temp = ""; + sType = sType.toUpperCase(); + sType = sType.trim(); + if (sType.equals("00")) + temp = "0001"; + if (sType.equals("02")) + temp = "1001"; + if (sType.equals("03")) + temp = "1011"; + if (sType.equals("04")) + temp = "1010"; + if (sType.equals("05")) + temp = "1010"; + if (sType.equals("06")) + temp = "1011"; + if (sType.equals("08")) + temp = "1011"; + if (sType.equals("09")) + temp = "1011"; + if (sType.equals("0A")) + temp = "1011"; + if (sType.equals("0B")) + temp = "1011"; + if (sType.equals("0C")) + temp = "1011"; + if (sType.equals("0D")) + temp = "1011"; + if (sType.equals("0E")) + temp = "1011"; + if (sType.equals("0F")) + temp = "1011"; + if (sType.equals("10")) + temp = "1011"; + if (sType.equals("8C")) + temp = "1011"; + if (sType.equals("A4")) + temp = "1010"; + if (sType.equals("A5")) + temp = "1010"; + if (sType.equals("AA")) + temp = "1011"; + if (sType.equals("AC")) + temp = "1011"; + if (sType.equals("AD")) + temp = "1011"; + if (bFCV) + temp = "01" + sFCB.substring(1, 2) + "1" + temp; + else + temp = "01" + sFCB.substring(1, 2) + "0" + temp; + return binaryString2Int(temp); + } + + private static Boolean CheckDwnPw(String sType) { + Boolean sign = false; + if (sType.equals("01")) + sign = true; + if (sType.equals("03")) + sign = true; + if (sType.equals("04")) + sign = true; + if (sType.equals("05")) + sign = true; + if (sType.equals("06")) + sign = true; + if (sType.equals("0F")) + sign = true; + if (sType.equals("10")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("01")) + sign = true; + if (sType.equals("A4")) + sign = true; + if (sType.equals("A5")) + sign = true; + return sign; + } + + /** + * 二进制字符串转整型 + * + * @param bString + * @return + */ + public static int binaryString2Int(String bString) { + int temp = 0; + for (int i = 0; i < bString.length(); i++) { + temp <<= 1; + temp += Integer.parseInt(bString.substring(i, i + 1)); + } + return temp; + } + + private static int GetCS(int len) { + int ics = 0; + for (int i = 6; i < len; i++) { + ics = ics + msg[i]; + } + return ics & 0xFF; + } + +} diff --git a/selfDevelop/target/classes/META-INF/MANIFEST.MF b/selfDevelop/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..bd2d96f --- /dev/null +++ b/selfDevelop/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: Administrator +Build-Jdk: 1.8.0_351 +Created-By: Maven Integration for Eclipse + diff --git a/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.properties b/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.properties new file mode 100644 index 0000000..64deafa --- /dev/null +++ b/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Jun 05 23:15:09 CST 2024 +version=0.0.1-SNAPSHOT +groupId=com.back +m2e.projectName=2-selfDevelop +m2e.projectLocation=D\:\\fyj_20240312\\processor\\selfDevelop +artifactId=selfDevelop diff --git a/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.xml b/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.xml new file mode 100644 index 0000000..1491b61 --- /dev/null +++ b/selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + + com.back + processor + 0.0.1-SNAPSHOT + + selfDevelop + jar + + + + com.back + common + 0.0.1-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.6.4 + + + com.back.main.MainProcess + ZIP + + + + + repackage + + + + + + + + + \ No newline at end of file