做modbus的通信客户端接口,需要双方约定:
1、协议:http/ip
2、ip、端口 :127.0.0.1 、502
3、参数条件:byte类型的参数条件
具体实现代码:
package com.chuang.service.impl;
import com.chuang.dao.TestTableDao;
import com.chuang.entity.ModbusCondition;
import com.chuang.entity.NextPosition;
import com.chuang.entity.TestTableEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@EnableScheduling
public class TimingTask {
@Autowired
TestTableDao testDao;
@Scheduled(cron = "0 0/5 * * * ?") //spring定时任务:周期5分钟
// @Scheduled(cron = "0/5 * * * * ?")
public void timeTskByModbusInsert(){
modbusPubMethd();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
}
public void modbusPubMethd(){
long startTime=System.currentTimeMillis();
TestTableEntity tableEntity = new TestTableEntity();
try {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String newTime = df.format(new Date());
System.out.println(newTime);// new Date()为获取当前系统时间
List mcList = testDao.queryModbusCondition();
if (mcList == null || mcList.size() <= 0)
throw new Exception("数据库ModbusCondition,modbus查询参数没有值");
Socket socket = new Socket("127.0.0.1",502);
OutputStream outputStream = socket.getOutputStream();
//参数条件
byte[] requestParam = ModbusUtil.getByteBycondition(mcList.get(0));
outputStream.write(requestParam);
InputStream inputStream = socket.getInputStream();
int length = -1;
byte[] bytes1 = new byte[1024];
int count = 0;
//循环读取socket服务端发送数据,直到没有数据返回-1为止
while ((length = inputStream.read(bytes1)) != -1) {
byte[] bytes = new byte[1024];
System.arraycopy(bytes1,0,bytes,0,length);
count++;
System.out.println("----------遍历数据次数:" + count);
System.out.println("----------length----" + length);
int flag = 1;
NextPosition fromPos = new NextPosition();
System.out.println(length);
// System.arraycopy(bytes1,0,bytes,0,bytes1.length);
System.out.println(Arrays.toString(bytes));
//以下代码是对服务端返回数据的解析,解析规则两边需要商定好,必须严格按照规则进行解析
while (fromPos.value < length) {
System.out.println(bytes);
short transFlag = 0;
short protocolIdentifier = 0;
short laterLength = 0;
byte unitFlag = 0;
byte functionCode = 0;
short alarmLength = 0;
if (flag == 1) {
transFlag = StreamToINT16(bytes, fromPos);
protocolIdentifier = StreamToINT16(bytes, fromPos);
laterLength = StreamToINT16(bytes, fromPos);
unitFlag = StreamToINT8(bytes, fromPos);
functionCode = StreamToINT8(bytes, fromPos);
alarmLength = StreamToINT16(bytes, fromPos);
flag++;
}
String ssid = StreamToString(bytes, fromPos, 2, 0);
String stationid = StreamToString(bytes, fromPos, 3, 0);
String machineid = StreamToString(bytes, fromPos, 3, 0);
String slotid = StreamToString(bytes, fromPos, 3, 0);
String alarmcodeG = StreamToString(bytes, fromPos, 2, 0);
String alarmcodeL = StreamToString(bytes, fromPos, 2, 0);
String yearG = StreamToString(bytes, fromPos, 2, 0);
String yearL = StreamToString(bytes, fromPos, 2, 0);
String month = StreamToString(bytes, fromPos, 2, 0);
String day = StreamToString(bytes, fromPos, 2, 0);
String hour = StreamToString(bytes, fromPos, 2, 0);
String min = StreamToString(bytes, fromPos, 2, 0);
String sec = StreamToString(bytes, fromPos, 2, 0);
tableEntity.setRecid(UUID.randomUUID().toString());
tableEntity.setSsid(ssid);
tableEntity.setCasstationid(stationid);
tableEntity.setMachineid(machineid);
tableEntity.setSlotid(slotid);
tableEntity.setAlarmcode(alarmcodeG + alarmcodeL);
tableEntity.setLatestTime(yearG + yearL + month + day + hour + min + sec);
tableEntity.setRecCreTime(newTime);
testDao.metinsert(tableEntity);
}
if (length<380) break;
}
inputStream.close();
outputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
System.out.println("开始时间:" + startTime + "---结束时间:" + endTime);
System.out.println("程序运行时间: "+(endTime - startTime)+"ms");
}
public static short StreamToINT16(byte[] fromStream, NextPosition fromPos)
{
short ret = 0;
short a0 = (short) (changeByte(fromStream[fromPos.value]));
short a1 = (short) (changeByte(fromStream[fromPos.value + 1]));
ret = (short) (a1 + (a0 << 8));
fromPos.value += 2;
return ret;
}
public static byte StreamToINT8(byte[] fromStream, NextPosition fromPos)
{
return fromStream[fromPos.value++];
}
public static String StreamToString(byte[] fromStream, NextPosition fromPos, int memLen, int strLen)
{
String toStr;
if (strLen < 0)
{
fromStream[memLen - 1] = 0;
strLen = memLen - 1;
}
if (strLen == 0)
{
int currPos = fromPos.value;
for (; currPos < fromStream.length && fromStream[currPos] != 0 && strLen < memLen; currPos++)
{
strLen++;
}
}
toStr = new String(fromStream, fromPos.value, strLen);
fromPos.value += memLen;
return toStr;
}
private static int changeByte(byte inByte)
{
if (inByte < 0)
{
return 256 + inByte;
}
else
{
return inByte;
}
}
}