集中器服务拆分

master
gdxs 2 years ago
commit c4fe9ca936
  1. 17
      carCheck/conn.properties
  2. 52
      carCheck/pom.xml
  3. 24
      carCheck/src/main/java/com/back/instance/WebsocketConnectInstance.java
  4. 65
      carCheck/src/main/java/com/back/main/MainProcess.java
  5. 1174
      carCheck/src/main/java/com/back/webSocket/CarCheckSocket.java
  6. 277
      carCheck/src/main/java/com/back/webSocket/SocketServer.java
  7. 27
      carCheck/src/main/java/com/back/webSocket/bean/BaseInfo.java
  8. 49
      carCheck/src/main/java/com/back/webSocket/bean/CarCheckInfo.java
  9. 106
      carCheck/src/main/java/com/back/webSocket/bean/CarSensor.java
  10. 154
      carCheck/src/main/java/com/back/webSocket/bean/FlowInfo.java
  11. 81
      carCheck/src/main/java/com/back/webSocket/bean/LineInfo.java
  12. 53
      carCheck/src/main/java/com/back/webSocket/bean/LoadInfo.java
  13. 125
      carCheck/src/main/java/com/back/webSocket/bean/SensorInfo.java
  14. 89
      carCheck/src/main/java/com/back/webSocket/bean/TargetInfo.java
  15. 5
      carCheck/target/classes/META-INF/MANIFEST.MF
  16. 7
      carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.properties
  17. 52
      carCheck/target/classes/META-INF/maven/com.back/carCheck/pom.xml
  18. 17
      carCheckNew/conn.properties
  19. 49
      carCheckNew/pom.xml
  20. 24
      carCheckNew/src/main/java/com/back/instance/WebsocketConnectInstance.java
  21. 66
      carCheckNew/src/main/java/com/back/main/MainProcess.java
  22. 1219
      carCheckNew/src/main/java/com/back/webSocket/CarCheckSocket.java
  23. 277
      carCheckNew/src/main/java/com/back/webSocket/SocketServer.java
  24. 27
      carCheckNew/src/main/java/com/back/webSocket/bean/BaseInfo.java
  25. 49
      carCheckNew/src/main/java/com/back/webSocket/bean/CarCheckInfo.java
  26. 106
      carCheckNew/src/main/java/com/back/webSocket/bean/CarSensor.java
  27. 156
      carCheckNew/src/main/java/com/back/webSocket/bean/FlowInfo.java
  28. 81
      carCheckNew/src/main/java/com/back/webSocket/bean/LineInfo.java
  29. 53
      carCheckNew/src/main/java/com/back/webSocket/bean/LoadInfo.java
  30. 125
      carCheckNew/src/main/java/com/back/webSocket/bean/SensorInfo.java
  31. 89
      carCheckNew/src/main/java/com/back/webSocket/bean/TargetInfo.java
  32. 5
      carCheckNew/target/classes/META-INF/MANIFEST.MF
  33. 7
      carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.properties
  34. 49
      carCheckNew/target/classes/META-INF/maven/com.back/carCheckNew/pom.xml
  35. 85
      common/pom.xml
  36. 167
      common/src/main/java/com/back/action/Log.java
  37. 689
      common/src/main/java/com/back/common/Common.java
  38. 50
      common/src/main/java/com/back/common/MeterTimingParams.java
  39. 11
      common/src/main/java/com/back/common/OpcDeviceParams.java
  40. 63
      common/src/main/java/com/back/common/RunParams.java
  41. 401
      common/src/main/java/com/back/jdbc/SQLHelper.java
  42. 518
      common/src/main/java/com/back/protocol/SystemParameter.java
  43. 336
      common/src/main/java/com/back/threadpool/ThreadPool.java
  44. 17
      common/src/main/resources/conn.properties
  45. 5
      common/target/classes/META-INF/MANIFEST.MF
  46. 7
      common/target/classes/META-INF/maven/com.back/common/pom.properties
  47. 85
      common/target/classes/META-INF/maven/com.back/common/pom.xml
  48. 17
      common/target/classes/conn.properties
  49. 17
      opc/conn.properties
  50. 52
      opc/pom.xml
  51. 353
      opc/src/main/java/com/back/action/Work.java
  52. 51
      opc/src/main/java/com/back/main/MainProcess.java
  53. 38
      opc/src/main/java/com/back/main/MythreadOpc.java
  54. 150
      opc/src/main/java/com/back/opcua/OpcUaUtil.java
  55. 66
      opc/src/main/java/com/back/protocol/Protocol.java
  56. 5
      opc/target/classes/META-INF/MANIFEST.MF
  57. 7
      opc/target/classes/META-INF/maven/com.back/opc/pom.properties
  58. 52
      opc/target/classes/META-INF/maven/com.back/opc/pom.xml
  59. 16
      pom.xml
  60. 17
      selfDevelop/conn.properties
  61. 53
      selfDevelop/pom.xml
  62. 3410
      selfDevelop/src/main/java/com/back/action/Work.java
  63. 30
      selfDevelop/src/main/java/com/back/communication/CmdObject485.java
  64. 266
      selfDevelop/src/main/java/com/back/communication/SendSMS.java
  65. 337
      selfDevelop/src/main/java/com/back/communication/SerialComm.java
  66. 1063
      selfDevelop/src/main/java/com/back/communication/SerialComm485.java
  67. 335
      selfDevelop/src/main/java/com/back/communication/SerialSMS.java
  68. 251
      selfDevelop/src/main/java/com/back/communication/SocketComm.java
  69. 922
      selfDevelop/src/main/java/com/back/communication/SocketComm485.java
  70. 253
      selfDevelop/src/main/java/com/back/communication/Wechat.java
  71. 115
      selfDevelop/src/main/java/com/back/communication/mail/MailSenderInfo.java
  72. 21
      selfDevelop/src/main/java/com/back/communication/mail/MyAuthenticator.java
  73. 110
      selfDevelop/src/main/java/com/back/communication/mail/SimpleMailSender.java
  74. 292
      selfDevelop/src/main/java/com/back/entity/Control.java
  75. 338
      selfDevelop/src/main/java/com/back/entity/Mcontrol.java
  76. 220
      selfDevelop/src/main/java/com/back/entity/Sensor.java
  77. 49
      selfDevelop/src/main/java/com/back/entity/SyncEntity.java
  78. 129
      selfDevelop/src/main/java/com/back/main/MainProcess.java
  79. 35
      selfDevelop/src/main/java/com/back/main/Mythreadgprs.java
  80. 488
      selfDevelop/src/main/java/com/back/protocol/BusinessParameter.java
  81. 3024
      selfDevelop/src/main/java/com/back/protocol/GW3761.java
  82. 262
      selfDevelop/src/main/java/com/back/protocol/GeneralString.java
  83. 553
      selfDevelop/src/main/java/com/back/protocol/LampOld.java
  84. 1318
      selfDevelop/src/main/java/com/back/protocol/Lon16.java
  85. 1448
      selfDevelop/src/main/java/com/back/protocol/Protocol.java
  86. 95
      selfDevelop/src/main/java/com/back/sync/DataInstance.java
  87. 666
      selfDevelop/src/main/java/com/back/sync/DataSyncUtil.java
  88. 5
      selfDevelop/target/classes/META-INF/MANIFEST.MF
  89. 7
      selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.properties
  90. 53
      selfDevelop/target/classes/META-INF/maven/com.back/selfDevelop/pom.xml

@ -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

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>carCheck</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -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;
}
}

@ -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());
}
}
}

@ -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<String, WebSocket> map = new ConcurrentHashMap<>();
public static Map<String, SocketBean> connectMap = new ConcurrentHashMap<>();
public static Map<String, Integer> 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<String, Object> map = new HashMap<String, Object>();
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<String, WebSocket> 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<String, SocketBean> 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;
}
}
}

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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<Flow> 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<Flow> getFlowList() {
return flowList;
}
public void setFlowList(List<Flow> 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;
}
}
}

@ -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;
}
}

@ -0,0 +1,53 @@
package com.back.webSocket.bean;
import java.util.List;
public class LoadInfo {
private Integer valid;
private Integer laneCount;
private List<Load> 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<Load> getLoadList() {
return loadList;
}
public void setLoadList(List<Load> 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;
}
}
}

@ -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<LaneWeight> 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<LaneWeight> getLaneList() {
return laneList;
}
public void setLaneList(List<LaneWeight> laneList) {
this.laneList = laneList;
}
}

@ -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<Target> 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<Target> getTargetList() {
return targetList;
}
public void setTargetList(List<Target> 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;
}
}
}

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Built-By: Administrator
Build-Jdk: 1.8.0_351
Created-By: Maven Integration for Eclipse

@ -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

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>carCheck</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -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

@ -0,0 +1,49 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>carCheckNew</artifactId>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -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;
}
}

@ -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());
}
}
}

@ -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<String, WebSocket> map = new ConcurrentHashMap<>();
public static Map<String, SocketBean> connectMap = new ConcurrentHashMap<>();
public static Map<String, Integer> 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<String, Object> map = new HashMap<String, Object>();
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<String, WebSocket> 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<String, SocketBean> 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;
}
}
}

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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<Flow> 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<Flow> getFlowList() {
return flowList;
}
public void setFlowList(List<Flow> 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;
}
}
}

@ -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;
}
}

@ -0,0 +1,53 @@
package com.back.webSocket.bean;
import java.util.List;
public class LoadInfo {
private Integer valid;
private Integer laneCount;
private List<Load> 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<Load> getLoadList() {
return loadList;
}
public void setLoadList(List<Load> 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;
}
}
}

@ -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<LaneWeight> 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<LaneWeight> getLaneList() {
return laneList;
}
public void setLaneList(List<LaneWeight> laneList) {
this.laneList = laneList;
}
}

@ -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<Target> 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<Target> getTargetList() {
return targetList;
}
public void setTargetList(List<Target> 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;
}
}
}

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Built-By: Administrator
Build-Jdk: 1.8.0_351
Created-By: Maven Integration for Eclipse

@ -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

@ -0,0 +1,49 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>carCheckNew</artifactId>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,85 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>common</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
<artifactId>rxtxcomm</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.scream3r</groupId>
<artifactId>jssc</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<!--Milo客户端的依赖-->
<dependency>
<groupId>org.eclipse.milo</groupId>
<artifactId>sdk-client</artifactId>
<version>0.6.3</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
</dependencies>
</project>

@ -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;
}
}
}

@ -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;
}
}

@ -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;
}

@ -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;
}

@ -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;//隧道用电分析
}

@ -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;
}
}

@ -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();
}
}

@ -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<Thread> workRun; // 工作队列
private LinkedList<Thread> 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<String> terminaList = new ArrayList<String>();
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<Thread>(); // 创建工作后继队列
workRun = new LinkedList<Thread>(); // 创建工作队列
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增加防止内存溢出
}
}
}
}

@ -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

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Built-By: Administrator
Build-Jdk: 1.8.0_351
Created-By: Maven Integration for Eclipse

@ -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

@ -0,0 +1,85 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>common</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
<artifactId>rxtxcomm</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.scream3r</groupId>
<artifactId>jssc</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<!--Milo客户端的依赖-->
<dependency>
<groupId>org.eclipse.milo</groupId>
<artifactId>sdk-client</artifactId>
<version>0.6.3</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
</dependencies>
</project>

@ -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

@ -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

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>opc</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -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<String,OpcDeviceData> 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<String> 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<String,OpcDeviceData> 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: ");
}
}
}

@ -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);
}
}

@ -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();
}
}
}
}

@ -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<EndpointDescription> collect = endpointDescriptions.stream().collect(Collectors.toList());
final Optional<EndpointDescription> 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<? extends UaNode> 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);
}
}
}

@ -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;
}
}
}

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Built-By: Administrator
Build-Jdk: 1.8.0_351
Created-By: Maven Integration for Eclipse

@ -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

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>opc</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>processor</name>
<description>processor</description>
<modules>
<module>common</module>
<module>selfDevelop</module>
<module>opc</module>
<module>carCheck</module>
<module>carCheckNew</module>
</modules>
</project>

@ -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

@ -0,0 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>selfDevelop</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

File diff suppressed because it is too large Load Diff

@ -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;
}
}

@ -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);
}*/
}

@ -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<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(5);
}
}
if (!isread) {// 超时处理
if (ruletype.equals("0001")) {// 旧协议
lon16.ResolvingData(cmdid,this.outdata, rterminal, "", 3, "0001", batchtime,taskidString);
} else if (ruletype.equals("0002")) {// 新协议 国网
gw3761.ResolvingData(cmdid, rterminal, "", 3, "0001", afncode, Fn, batchtime, taskidString,this.outdata);
}
Log.writelog(clazzName,Thread.currentThread().getStackTrace()[1].getMethodName() + "->[" + 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);
}
}
}

@ -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;
}
}
}

@ -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);
}
}
}

@ -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<CmdObject485> cmdQueue = new LinkedList<CmdObject485>(); // 命令处理队列
private List<String> termina485lList = new ArrayList<String>(); // 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 (ec<dbec)
y= y + 256;
if (y>20)
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();
}
}

@ -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<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>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;
}
}
}

@ -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;
}
}

@ -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);
}
}

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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;
}
}

@ -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);
}
}

@ -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();
}
}
}
}

@ -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;
}
}
}

File diff suppressed because it is too large Load Diff

@ -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();
}
}

@ -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;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -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<Control> controlList;
private List<Mcontrol> mcontrolList;
// 照度
private List<Sensor> illumList;
// 亮度
private List<Sensor> lumList;
// 车流量
private List<Sensor> carsenList;
private int totalCount;
private int syncedCount;
private int progress;
// 命令发送状态
private int state;
public List<Control> getControlList() {
return controlList;
}
public void setControlList(List<Control> controlList) {
this.controlList = controlList;
}
public List<Mcontrol> getMcontrolList() {
return mcontrolList;
}
public void setMcontrolList(List<Mcontrol> mcontrolList) {
this.mcontrolList = mcontrolList;
}
public List<Sensor> getIllumList() {
return illumList;
}
public void setIllumList(List<Sensor> illumList) {
this.illumList = illumList;
}
public List<Sensor> getLumList() {
return lumList;
}
public void setLumList(List<Sensor> lumList) {
this.lumList = lumList;
}
public List<Sensor> getCarsenList() {
return carsenList;
}
public void setCarsenList(List<Sensor> 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;
}
}

@ -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<Control> 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<Control> 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<Mcontrol> 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<Sensor> 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<Mcontrol> 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<Sensor> 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;
}
}

@ -0,0 +1,5 @@
Manifest-Version: 1.0
Built-By: Administrator
Build-Jdk: 1.8.0_351
Created-By: Maven Integration for Eclipse

@ -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

@ -0,0 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.back</groupId>
<artifactId>processor</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>selfDevelop</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.back</groupId>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
<configuration>
<!-- springboot main方法入口 -->
<mainClass>com.back.main.MainProcess</mainClass>
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Loading…
Cancel
Save