springboot中modbus使用
pom.xml配置:
false
true
ias-snapshots
Infinite Automation Snapshot Repository
true
false
ias-releases
Infinite Automation Release Repository
https://maven.mangoautomation.net/repository/ias-release/
com.infiniteautomation
modbus4j
3.0.3
modbus配置类:
package com.induo.common.modbus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.induo.domain.mapper.IpControlMapper;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;
import java.util.HashMap;
@Configuration
/*
* 使用@Bean,就不用使用@Import来导入相应的类了,@Bean生成的bean的名字默认为方法名,由于hashMap使用很广泛,
* 所以使用@Bean的方式引入依赖,这样在注入的时候可以指定名称,以免注入错误的对象
* @Import({java.util.HashMap.class,com.serotonin.modbus4j.ModbusFactory.class})
*/
@Import(com.serotonin.modbus4j.ModbusFactory.class)
public class ModbusConfig {
@Bean
public HashMap modbusMasterHashMap() {
return new HashMap<>();
}
@Autowired
IpControlMapper ipControlMapper;
@Autowired
private ModbusFactory modbusFactory;
@Autowired
@Qualifier("modbusMasterHashMap")
private HashMap masterMap;
/**
* @Title getMaster
* @Description: 通过ip获取对应的modbus连接器
* @params: [ip]
* @return: com.serotonin.modbus4j.ModbusMaster
* @author: caiwei
* @date: 2019/5/1 13:58
*/
public ModbusMaster getMaster(String ip) {
ModbusMaster modbusMaster = masterMap.get(ip);
if(modbusMaster == null) {
setMaster(ip, ipControlMapper.queryControlByIp(ip).getPort());
modbusMaster = masterMap.get(ip);
}
return modbusMaster;
}
/**
* @Title setMaster
* @Description: 设置ip对应的modbus连接器
* @params: [ip, port]
* @return: void
* @author: caiwei
* @date: 2019/5/1 13:59
*/
private void setMaster(String ip, Integer port) {
ModbusMaster master;
IpParameters params = new IpParameters();
params.setHost(ip);
params.setPort(port);
//设置为true,会导致TimeoutException: request=com.serotonin.modbus4j.ip.encap.EncapMessageRequest@774dfba5",
//params.setEncapsulated(true);
master = modbusFactory.createTcpMaster(params, false);// TCP 协议
try {
//设置超时时间
master.setTimeout(3*1000);
//设置重连次数
master.setRetries(3);
//初始化
master.init();
} catch (ModbusInitException e) {
e.printStackTrace();
}
masterMap.put(ip, master);
}
}
modbus工具类:
package com.induo.common.modbus;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @ClassName: ModbusUtil
* @Description: modbus读写工具类
* @auther: caiwei
* @date: 2019/5/1 15:44
*/
@Component
public class ModbusUtil {
//从机默认值
private Integer slaveId = 1;
@Autowired
private ModbusConfig modbusConfig;
/**
* @Title readCoilStatus
* @Description: 读(线圈)开关量数据,相当于功能码:01H-读线圈状态
* @params: [ip, slaveId, offset, numberOfRegister]
* @return: boolean[]
* @throws:
* @author: caiwei
* @date: 2019/5/1 14:32
*/
public boolean[] readCoilStatus(String ip, int offset, int numberOfRegister) throws ModbusTransportException {
ModbusMaster master = modbusConfig.getMaster(ip);
ReadCoilsRequest request = new ReadCoilsRequest(slaveId, offset, numberOfRegister);
ReadCoilsResponse response = (ReadCoilsResponse) master.send(request);
boolean[] booleans = response.getBooleanData();
return valueRegroup(numberOfRegister, booleans);
}
/**
* @Title readInputStatus
* @Description: 读取外围设备输入的开关量,相当于功能码:02H-读离散输入状态
* @params: [ip, offset, numberOfRegister]
* @return: boolean[]
* @throws:
* @author: caiwei
* @date: 2019/5/1 14:49
*/
public boolean[] readInputStatus(String ip, int offset, int numberOfRegister) throws ModbusTransportException {
ModbusMaster master = modbusConfig.getMaster(ip);
ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId,offset, numberOfRegister);
ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) master.send(request);
boolean[] booleans = response.getBooleanData();
return valueRegroup(numberOfRegister, booleans);
}
/**
* @Title readHoldingRegister
* @Description: 读取保持寄存器数据,相当于功能码:03H-读保持寄存器
* @params: [ip, offset, numberOfRegister]
* @return: short[]
* @throws:
* @author: caiwei
* @date: 2019/5/1 15:53
*/
public short[] readHoldingRegister(String ip, int offset, int numberOfRegister) throws ModbusTransportException {
ModbusMaster master = modbusConfig.getMaster(ip);
ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, offset, numberOfRegister);
ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
return response.getShortData();
}
/**
* @Title readInputRegisters
* @Description: 读取外围设备输入的数据,相当于功能码:04H-读输入寄存器
* @params: [ip, offset, numberOfRegister]
* @return: short[]
* @throws:
* @author: caiwei
* @date: 2019/5/1 15:56
*/
public short[] readInputRegisters(String ip, int offset, int numberOfRegister) throws ModbusTransportException {
ModbusMaster master = modbusConfig.getMaster(ip);
ReadInputRegistersRequest request = new ReadInputRegistersRequest(slaveId, offset, numberOfRegister);
ReadInputRegistersResponse response = (ReadInputRegistersResponse) master.send(request);
return response.getShortData();
}
/**
* @Title writeCoil
* @Description: 写单个(线圈)开关量数据,相当于功能码:05H-写单个线圈
* @params: [ip, writeOffset, writeValue]
* @return: boolean
* @throws:
* @author: caiwei
* @date: 2019/5/1 16:00
*/
public boolean writeCoil(String ip, int writeOffset, boolean writeValue) throws ModbusTransportException {
ModbusMaster tcpMaster = modbusConfig.getMaster(ip);
WriteCoilRequest request = new WriteCoilRequest(slaveId, writeOffset, writeValue);
WriteCoilResponse response = (WriteCoilResponse) tcpMaster.send(request);
return !response.isException();
}
/**
* @Title writeCoils
* @Description: 写多个开关量数据(线圈),相当于功能码:0FH-写多个线圈
* @params: [ip, startOffset, data]
* @return: boolean
* @throws:
* @author: caiwei
* @date: 2019/5/1 16:00
*/
public boolean writeCoils(String ip, int startOffset, boolean[] data) throws ModbusTransportException {
ModbusMaster tcpMaster = modbusConfig.getMaster(ip);
WriteCoilsRequest request = new WriteCoilsRequest(slaveId, startOffset, data);
WriteCoilsResponse response = (WriteCoilsResponse) tcpMaster.send(request);
return !response.isException();
}
/**
* @Title writeHoldingRegister
* @Description: 写单个保持寄存器,相当于功能码:06H-写单个保持寄存器
* @params: [ip, writeOffset, writeValue]
* @return: boolean
* @throws:
* @author: caiwei
* @date: 2019/5/1 16:02
*/
public boolean writeHoldingRegister(String ip, int writeOffset, short writeValue) throws ModbusTransportException, ModbusInitException {
ModbusMaster tcpMaster = modbusConfig.getMaster(ip);
WriteRegisterRequest request = new WriteRegisterRequest(slaveId, writeOffset, writeValue);
WriteRegisterResponse response = (WriteRegisterResponse) tcpMaster.send(request);
return !response.isException();
}
/**
* @Title writeHoldingRegisters
* @Description: 写多个保持寄存器,相当于功能码:10H-写多个保持寄存器
* @params: [ip, slaveId, startOffset, data]
* @return: boolean
* @throws:
* @author: caiwei
* @date: 2019/5/1 16:03
*/
public boolean writeHoldingRegisters(String ip, int startOffset, short[] data) throws ModbusTransportException, ModbusInitException {
ModbusMaster tcpMaster = modbusConfig.getMaster(ip);
WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, data);
WriteRegistersResponse response = (WriteRegistersResponse) tcpMaster.send(request);
return !response.isException();
}
/**
* @Title valueRegroup
* @Description: 转换工具,将Boolean转换成0,1
* @params: [numberOfBits, values]
* @return: boolean[]
* @throws:
* @author: caiwei
* @date: 2019/5/1 15:55
*/
private boolean[] valueRegroup(int numberOfBits, boolean[] values) {
boolean[] bs = new boolean[numberOfBits];
int temp = 1;
for (boolean b : values) {
bs[temp - 1] = b;
temp++;
if (temp > numberOfBits) {
break;
}
}
return bs;
}
}
ipControlMapper:
package com.induo.area.domain.mapper;
import java.util.List;
import com.induo.area.domain.entity.IpControl;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface IpControlMapper {
@Results(id = "ipControlMap", value = {
@Result(column = "ip", property = "ip", javaType = String.class),
@Result(column = "port", property = "port", javaType = Integer.class),
@Result(column = "ip_type", property = "ipType", javaType = Integer.class),
@Result(column = "device_data_gather_cycle", property = "deviceDataGatherCycle", javaType = Integer.class),
@Result(column = "device_data_gather_interval", property = "deviceDataGatherInterval", javaType = Integer.class),
@Result(column = "note_alarm_data_gather_cycle", property = "noteAlarmDataGatherCycle", javaType = Integer.class),
@Result(column = "environment_data_gather_cycle", property = "environmentDataRecordCycle", javaType = Integer.class)
}) 无锡人流医院哪家好 http://mobile.wxbhnkyy120.com/
//通过ip查询控制器
@Select("select ip, port, ip_type, device_data_gather_cycle, device_data_gather_interval, note_alarm_data_gather_cycle, environment_data_gather_cycle " +
"from control " +
"where ip = #{ip}")
IpControl queryControlByIp(String ip);
//通过ip类型(0:区域控制器, 1:八防控制器)查询控制器
@Select("select ip " +
"from control " +
"where ip_type = #{ipType}")
List queryAllIpControlIp(String ipType);
//插入控制器
@Insert("insert into control(ip, port, ip_type, device_data_gather_cycle, device_data_gather_interval, note_alarm_data_gather_cycle, environment_data_gather_cycle) " +
"values (#{ip}, #{port}, #{ipType}, #{deviceDataGatherCycle}, #{deviceDataGatherInterval}, #{noteAlarmDataGatherCycle}, #{environmentDataRecordCycle})")
void addIpControl(IpControl ipControl);
//更新区域控制器
@Update("")
void updateIpControl(IpControl ipControl);
//通过ip删除相应的控制器
@Delete("delete " +
"from control " +
"where ip = #{ip}")
void deleteIpControl(String ip);
}
springboot中modbus使用的更多相关文章
- SpringBoot中yaml配置对象
转载请在页首注明作者与出处 一:前言 YAML可以代替传统的xx.properties文件,但是它支持声明map,数组,list,字符串,boolean值,数值,NULL,日期,基本满足开发过程中的所 ...
- 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧
做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...
- springboot中swaggerUI的使用
demo地址:demo-swagger-springboot springboot中swaggerUI的使用 1.pom文件中添加swagger依赖 2.从github项目中下载swaggerUI 然 ...
- spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架
前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...
- 由浅入深学习springboot中使用redis
很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...
- Springboot中使用AOP统一处理Web请求日志
title: Springboot中使用AOP统一处理Web请求日志 date: 2017-04-26 16:30:48 tags: ['Spring Boot','AOP'] categories: ...
- SpringBoot 中常用注解
本篇博文将介绍几种SpringBoot 中常用注解 其中,各注解的作用为: @PathVaribale 获取url中的数据 @RequestParam 获取请求参数的值 @GetMapping 组合注 ...
- SpringBoot中关于Mybatis使用的三个问题
SpringBoot中关于Mybatis使用的三个问题 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8495453.html 原本是要讲讲PostgreSQL ...
- 在SpringBoot中配置aop
前言 aop作为spring的一个强大的功能经常被使用,aop的应用场景有很多,但是实际的应用还是需要根据实际的业务来进行实现.这里就以打印日志作为例子,在SpringBoot中配置aop 已经加入我 ...
随机推荐
- log配置文件log4j.propeties(配置保存日志文件的相对路径)
log配置文件log4j.propeties(配置保存日志文件的相对路径) log4j.propeties文件: #日志的4种级别ERROR(错误).WARN(警告潜在的错误).INFO(粗粒度信息) ...
- MySQL导数据笔记
2019-12-16 9:08:43 星期一 MySQL 5.6 limit / order 有bug, 如果主键不是自增的, 只能全表导出导入, 增量导入导出的话会报主键重复 触发器: 批量导入数据 ...
- Sword 哈希表
哈希表 哈希表是一种典型的以空间换取时间的数据结构,在没有冲突的情况下,对任意元素的插入.索引.删除的时间复杂度都是O().这样优秀的时间复杂度是通过将元素的key值以hash方法f映射到哈希表中的某 ...
- Numa 常用命令
1. 查看numa相关信息,包括每个node内存大小,每个node中的逻辑cpu: numactl --hardware
- SQL 对比,移动累计
数据对比 两种常用模型 1.对比下一行,判断增长.减少.维持现状 -- 建表 drop table sales create table sales( num int, soc int ); inse ...
- 【翻译】Flink Table Api & SQL — Hive —— Hive 函数
本文翻译自官网:Hive Functions https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/table/hive/h ...
- EasyDSS高性能RTMP、HLS(m3u8)、HTTP-FLV、RTSP流媒体服务器启用https服务申请免费证书
背景分析 目前想在 web 上使用 HTTPS 的话, 你需要获得一个证书文件, 该证书由一个受浏览器信任的公司所签署. 一旦你获得了它, 你就在你的 web 服务器上指定其所在的位置, 以及与你关联 ...
- linux服务器之间文件传输
有时候我们会遇到,把一个服务器上的文件夹,传到另一个服务器 我们需要先把文件夹打包成 tar.gz,这种格式在任何linux版本上都能压缩/解压 #解压命令 tar -zxvf xxx.tar.gz ...
- scrollview的优化
针对一次加载很多格子的scrollview的优化,第一次只加载可视区域的格子,其他的用空物体占位,在每次滑动时检测需要实例化的格子,通过对象池重用第一次的格子.可以根据每行格子的数量只检测每行的第一个 ...
- javascript (0, obj.prop)()的用法
我第一次看到这种奇怪的用法是在babel的源码中, 其实它的原理就是使得在prop这个方法里无法获取this, 从而无法对类中的其他变量或方法做操作. obj.prop() 这是一个方法调用, pro ...