package com.hcs.base;
import com.hcs.util.DebugUtil;
import com.hcs.weather.utils.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
/**
* 计算机连接网口
*
* @author lwt
* @date 2018/07/15
* @since 0.1.0
*/
public class PlcSocket {
public enum CODE_TYPE {
ASCII, //普通文本发送
HEX //十六进制发送
}
/**
* ip
*/
private String ip;
/**
* 端口
*/
private int port;
/**
* 数据长度(对于定长值为0)
*/
private int dataLength;
/**
* 编码方式
*/
private String codeType;
/**
* 等待时间
*/
private static final int DEFAULT_RANGE_FOR_SLEEP = 50;
/**
* 超时时间
*/
private static final int DEFAULT_RANGE_TIME_OUT = 1000 * 60;
/**
* socket
*/
private Socket socket = null;
@Autowired
private DebugUtil debugUtil;
/**
* logger
*/
private final Logger logger = LoggerFactory.getLogger(PlcSocket.class);
public PlcSocket(String ip, int port, int dataLength, String codeType) {
this.ip = ip;
this.port = port;
this.dataLength = dataLength;
this.codeType = codeType;
if (!debugUtil.isDebug()) {
try {
socket = new Socket(ip, port);
socket.setKeepAlive(true);
} catch (Exception e) {
logger.error("socket连接失败", e);
}
}
}
public synchronized String sendComm(String command) {
if (debugUtil.isDebug()) {
return "";
}
if (socket == null) {
int i = 0;
while (socket == null && i < 3) {
try {
socket = new Socket(ip, port);
socket.setKeepAlive(true);
} catch (IOException e) {
logger.error("socket连接失败", e);
}
try {
Thread.sleep(DEFAULT_RANGE_FOR_SLEEP);
} catch (InterruptedException e) {
logger.error("系统内部错误", e);
}
i++;
}
}
//超时
try {
socket.setSoTimeout(DEFAULT_RANGE_TIME_OUT);
} catch (SocketException e) {
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
socket = null;
return "";
}
//向网口发送数据
OutputStream os = null;
try {
os = socket.getOutputStream();
if (codeType.equals(CODE_TYPE.HEX.name())) {
os.write(HexUtil.decode(command));
} else {
OutputStreamWriter opsw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(opsw);
bw.write(command);
}
os.flush();
} catch (Exception e) {
logger.error("向PLC发送命令失败!", e);
return "";
}
//读取数据
String result = "";
InputStream inputStream = null;
try {
Thread.sleep(DEFAULT_RANGE_FOR_SLEEP);
inputStream = socket.getInputStream();
if (dataLength == 0) {
//定长有换行符
InputStreamReader ipsr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(ipsr);
result = br.readLine();
} else {
byte[] buffer = new byte[dataLength];
int len = -1;
if ((len = inputStream.read(buffer)) != -1) {
result = HexUtil.encode(buffer);
}
}
} catch (Exception e) {
logger.error("读取Socket信息失败", e);
}
return result;
}
public boolean connect() {
return true;
}
}