JAVA采用S7通信协议访问西门子PLC

简介

采用java的方式实现西门子S7协议

链接地址iot-communication
github: https://github.com/xingshuangs/iot-communication
gitee: https://gitee.com/xingshuang/iot-communication

  • 支持单数据读写,多数据读写,大数据量自动分包读写
  • 支持序列化批量多地址且地址不连续的读写
  • 支持读取DB区,I区,Q区,M区,V
  • 支持读取西门子S1200,200Smart
  • 支持PLC自动重连

引入依赖包

<dependency>
    <groupId>com.github.xingshuangs</groupId>
    <artifactId>iot-communication</artifactId>
    <version>1.5.2</version>
</dependency>

简单入门示例

class Demo {
    public static void main(String[] args) {
		// 创建PLC对象
		S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");
		// 读写boolean
		s7PLC.writeBoolean("DB1.2.0", true);
		boolean boolData = s7PLC.readBoolean("DB1.2.0");
		// 读写字节
		s7PLC.writeByte("DB2.1", (byte) 0x11);
		byte byteData = s7PLC.readByte("DB2.1");
    }
}

知识点1:地址读写格式以及对应含义(兼容大小写)

简写区域字节索引位索引PLC
DB1.1.2DB1区121200
DB2DB2区001200
DB3.3DB3区301200
D1.1.2DB1区121200
Q1.6Q区161200
Q1Q区101200
I2.5I区251200
I2I区201200
M3.2M区321200
M3M区301200
V2.1V区21200Smart
V2V区20200Smart

知识点2:访问数据类型与JAVA数据类型和PLC数据类型对应关系

访问数据类型数据类型名称数据大小(位)数据大小(字节)对应JAVA数据类型对应PLC数据类型示例
boolean布尔类型11/8BooleanBOOLtrue
byte字节类型81ByteBYTE0x11
uint16无符号2字节整型162IntegerWORD/UINT65535
int16有符号2字节整型162ShortWORD/INT-32760
uint32无符号4字节整型324LongDWORD/UDINT70000
int32有符号4字节整型324IntegerDWORD/DINT-70000
float324字节浮点型324FloatREAL3.14
float648字节浮点型648DoubleLREAL3.14
string字符型81StringStringABC

多种方式PLC数据访问示例

1. 单地址数据读写

// 创建PLC对象
S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");

// read boolean
boolean boolData = s7PLC.readBoolean("DB1.2.0");
// read byte
byte byteData = s7PLC.readByte("DB14.0");
byte iByteData = s7PLC.readByte("I0");
byte qByteData = s7PLC.readByte("Q0");
byte mByteData = s7PLC.readByte("M0");
byte vByteData = s7PLC.readByte("V0"); // 200smart有V区
// read byte
byte[] byteDatas = s7PLC.readByte("DB14.0", 4);
// read UInt16
int intData = s7PLC.readUInt16("DB14.0");
// read UInt32
long int32Data = s7PLC.readUInt32("DB1.0");
// read float32
float float32Data = s7PLC.readFloat32("DB1.0");
// read float64
double float64Data = s7PLC.readFloat64("DB1.0");
// read String
String strData = s7PLC.readString("DB14.4");

// write boolean
s7PLC.writeBoolean("DB2.0.7", true);
s7PLC.writeBoolean("Q0.7", true);
s7PLC.writeBoolean("M1.4", true);
// write byte
s7PLC.writeByte("DB2.1", (byte) 0x11);
s7PLC.writeByte("M1", (byte) 0x11);
s7PLC.writeByte("V1", (byte) 0x11); // 200smart有V区
// write UInt16
s7PLC.writeUInt16("DB2.0", 0x2222);
// write UInt32
s7PLC.writeUInt32("DB2.0", 0x11111122);
// write float32
s7PLC.writeFloat32("DB2.0", 12);
// write float64
s7PLC.writeFloat64("DB2.0", 12.02);
// write String
s7PLC.writeString("DB14.4", "demo");

2. 多地址数据读写

// 创建PLC对象
S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");

// read boolean
List<Boolean> boolDatas = s7PLC.readBoolean("DB1.2.0", "DB1.2.1", "DB1.2.7");
List<Boolean> iDatas = s7PLC.readBoolean("I0.0", "I0.1", "I0.2", "I0.3", "I0.4", "I0.5");
List<Boolean> qDatas = s7PLC.readBoolean("Q0.0", "Q0.1", "Q0.2", "Q0.3", "Q0.4", "Q0.5", "Q0.6", "Q0.7");
List<Boolean> mDatas = s7PLC.readBoolean("M1.0", "M1.1", "M1.2", "M1.3", "M1.4", "M1.5", "M1.6", "M1.7");
List<Boolean> vDatas = s7PLC.readBoolean("V1.0", "V1.1", "V1.2", "V1.3", "V1.4", "V1.5", "V1.6", "V1.7"); // 200smart有V区
// read UInt16
List<Integer> intDatas = s7PLC.readUInt16("DB1.0", "DB1.2");
// read UInt32
List<Long> int32Datas = s7PLC.readUInt32("DB1.0", "DB1.4");
// read float32
List<Float> float32Datas = s7PLC.readFloat32("DB1.0", "DB1.4");
// read float64
List<Double> float64Datas = s7PLC.readFloat64("DB1.0", "DB1.4");
// read multi address
MultiAddressRead addressRead = new MultiAddressRead();
addressRead.addData("DB1.0", 1)
           .addData("DB1.2", 3)
           .addData("DB1.3", 5);
List<byte[]> multiByte = s7PLC.readMultiByte(addressRead);

// write multi address
MultiAddressWrite addressWrite = new MultiAddressWrite();
addressWrite.addByte("DB2.0", (byte) 0x11)
            .addUInt16("DB2.2", 88)
            .addBoolean("DB2.1.0", true);
s7PLC.writeMultiData(addressWrite);

3. 序列化方式小数据量批量读写

小数据量是指单次数据请求的报文中PDU大小未超过指定PLC的最大值限制,例如单次请求PDULength小于240,不同PLC的限制各有不同,有240,480,960

先构建数据对象

@Data
public class DemoBean {

    @S7Variable(address = "DB1.0.1", type = EDataType.BOOL)
    private boolean bitData;

    @S7Variable(address = "DB1.1", type = EDataType.BYTE, count = 3)
    private byte[] byteData;

    @S7Variable(address = "DB1.4", type = EDataType.UINT16)
    private int uint16Data;

    @S7Variable(address = "DB1.6", type = EDataType.INT16)
    private short int16Data;

    @S7Variable(address = "DB1.8", type = EDataType.UINT32)
    private long uint32Data;

    @S7Variable(address = "DB1.12", type = EDataType.INT32)
    private int int32Data;

    @S7Variable(address = "DB1.16", type = EDataType.FLOAT32)
    private float float32Data;

    @S7Variable(address = "DB1.20", type = EDataType.FLOAT64)
    private double float64Data;
}

然后构建序列化对象,接着数据读写

class Demo {
    public static void main(String[] args) {
        S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");
        S7Serializer s7Serializer = S7Serializer.newInstance(s7PLC);
        // 小数据量批量读取
        DemoBean bean = s7Serializer.read(DemoBean.class);
        // 修改指定数据内容
        bean.setBitData(true);
        bean.setByteData(new byte[]{(byte) 0x01, (byte) 0x02, (byte) 0x03});
        bean.setUint16Data(42767);
        bean.setInt16Data((short) 32767);
        bean.setUint32Data(3147483647L);
        bean.setInt32Data(2147483647);
        bean.setFloat32Data(3.14f);
        bean.setFloat64Data(4.15);
        // 小数据量批量写入
        s7Serializer.write(bean);
    }
}

4. 序列化方式大数据量批量读写

大数据量是指单次数据请求的报文中PDU大小超过指定PLC的最大值限制,例如单次请求PDULength不得超过240,不同PLC的限制各有不同,有240,480,960

先构建数据对象

@Data
public class DemoLargeBean {

    @S7Variable(address = "DB1.0.1", type = EDataType.BOOL)
    private boolean bitData;

    @S7Variable(address = "DB1.10", type = EDataType.BYTE, count = 50)
    private byte[] byteData1;

    @S7Variable(address = "DB1.60", type = EDataType.BYTE, count = 65)
    private byte[] byteData2;

    @S7Variable(address = "DB1.125", type = EDataType.BYTE, count = 200)
    private byte[] byteData3;

    @S7Variable(address = "DB1.325", type = EDataType.BYTE, count = 322)
    private byte[] byteData4;

    @S7Variable(address = "DB1.647", type = EDataType.BYTE, count = 99)
    private byte[] byteData5;

    @S7Variable(address = "DB1.746", type = EDataType.BYTE, count = 500)
    private byte[] byteData6;

    @S7Variable(address = "DB1.1246", type = EDataType.BYTE, count = 44)
    private byte[] byteData7;
}

然后构建序列化对象,接着数据读写

class Demo {
    public static void main(String[] args) {
        S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");
        S7Serializer s7Serializer = S7Serializer.newInstance(s7PLC);
        // 大数据量批量读取
        DemoLargeBean bean = s7Serializer.read(DemoLargeBean.class);
        // 指定地址数据更改
        bean.getByteData2()[64] = (byte) 0x02;
        bean.getByteData3()[199] = (byte) 0x03;
        bean.getByteData4()[321] = (byte) 0x04;
        bean.getByteData5()[98] = (byte) 0x05;
        bean.getByteData6()[499] = (byte) 0x06;
        bean.getByteData7()[43] = (byte) 0x07;
        // 大数据量批量写入
        s7Serializer.write(bean);
    }
}

5. 自定义读写方式(开发效率低)

class Demo {
    public static void main(String[] args) {
        S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");
        // bit数据读写
        byte[] expect = new byte[]{(byte) 0x00};
        this.s7PLC.writeRaw(EParamVariableType.BIT, 1, EArea.DATA_BLOCKS, 1, 0, 3,
                EDataVariableType.BIT, expect);
        byte[] actual = this.s7PLC.readRaw(EParamVariableType.BIT, 1, EArea.DATA_BLOCKS, 1, 0, 3);
		// byte数据读写
        expect = new byte[]{(byte) 0x02, (byte) 0x03};
        this.s7PLC.writeRaw(EParamVariableType.BYTE, 2, EArea.DATA_BLOCKS, 1, 1, 0,
                EDataVariableType.BYTE_WORD_DWORD, expect);
        actual = this.s7PLC.readRaw(EParamVariableType.BYTE, 2, EArea.DATA_BLOCKS, 1, 1, 0);
    }
}

6. 控制指令

class Demo {
    public static void main(String[] args) {
        S7PLC s7PLC = new S7PLC(EPlcType.S1200, "127.0.0.1");
        // hot restart
        s7PLC.hotRestart();
        // cold restart
        s7PLC.coldRestart();
        // plc stop
        s7PLC.plcStop();
        // copy ram to rom
        s7PLC.copyRamToRom();
        // compress
        s7PLC.compress();
    }
}

字节数据解析

当采集的数据量比较大且都是字节数组数据时,需要将字节数据转换成所需的数据,可以采用ByteReadBuff工具;
该工具采用大端模式,4字节数据解析采用DCBA,可根据需求自行修改;

1. boolean数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x55});
// 直接字节解析获取,内部索引自动后移
boolean b1 = buff.getBoolean(0);
// 指定字节索引地址后解析获取
boolean b2 = buff.getBoolean(0, 1);

2. byte数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x55, (byte) 0x33, (byte) 0x22});
// 先提取第一个字节
buff.getByte();
// 再提取后两个字节
byte[] actual = buff.getBytes(2);
assertArrayEquals(new byte[]{(byte) 0x33, (byte) 0x22}, actual);

buff = new ByteReadBuff(new byte[]{(byte) 0x55, (byte) 0x33, (byte) 0x22});
// 先提取第一个字节
buff.getByte();
// 再提取剩余所有字节
actual = buff.getBytes();
assertArrayEquals(new byte[]{(byte) 0x33, (byte) 0x22}, actual);

3. uint16数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x5F, (byte) 0xF5});
int actual = buff.getUInt16();
assertEquals(24565, actual);

4. int16数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x5F, (byte) 0xF5});
short actual = buff.getInt16();
assertEquals(24565, actual);

5. uint32数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x00, (byte) 0x20, (byte) 0x37, (byte) 0x36});
long actual = buff.getUInt32();
assertEquals(2111286L, actual);

6. int32数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x00, (byte) 0x20, (byte) 0x37, (byte) 0x36});
int actual = buff.getInt32();
assertEquals(2111286, actual);

7. float32数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x42, (byte) 0x04, (byte) 0xA3, (byte) 0xD7});
float actual = buff.getFloat32();
assertEquals(33.16f, actual, 0.001);

8. float64数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x41, (byte) 0x03, (byte) 0x1F, (byte) 0xCA, (byte) 0xD6, (byte) 0x21, (byte) 0x39, (byte) 0xB7});
double actual = buff.getFloat64();
assertEquals(156665.35455556, actual, 0.001);

9. string数据类型

ByteReadBuff buff = new ByteReadBuff(new byte[]{(byte) 0x30, (byte) 0x31, (byte) 0x32, (byte) 0x33});
String actual = buff.getString(4);
assertEquals("0123", actual);

Springboot中简单使用

1. 普通模式

先构建Springboot的工程,添加maven依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.xingshuangs/iot-communication -->
        <dependency>
            <groupId>com.github.xingshuangs</groupId>
            <artifactId>iot-communication</artifactId>
            <version>1.5.2</version>
        </dependency>
    </dependencies>

添加PLC相关配置,主要是对连接对象实例化,创建bean

package com.github.xingshuangs.s7.demo.config;

import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.serializer.S7Serializer;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xingshuang
 */
@Configuration
public class S7Config {

    @Bean
    public S7PLC s7PLC() {
        return new S7PLC(EPlcType.S1200, "127.0.0.1");
    }
}

添加控制层业务

package com.github.xingshuangs.s7.demo.controller;

import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author xingshuang
 */
@RestController
@RequestMapping("/normal")
public class S7NormalComController {
    Random random = new Random();

    @Autowired
    private S7PLC s7PLC;

    @GetMapping("/uint16")
    public ResponseEntity uint16() {
        this.s7PLC.writeUInt16("DB1.0", random.nextInt(255));
        int res = this.s7PLC.readUInt16("DB1.0");
        return ResponseEntity.ok(res);
    }

    @GetMapping("/boolean")
    public ResponseEntity booleanTest() {
        this.s7PLC.writeBoolean("DB1.0.0", random.nextInt(255) % 2 == 0);
        boolean res = this.s7PLC.readBoolean("DB1.0.0");
        return ResponseEntity.ok(res);
    }

    @GetMapping("/float32")
    public ResponseEntity float32Test() {
        this.s7PLC.writeFloat32("DB1.0", random.nextFloat());
        float res = this.s7PLC.readFloat32("DB1.0");
        return ResponseEntity.ok(res);
    }

    @GetMapping("/string")
    public ResponseEntity stringTest() {
        this.s7PLC.writeString("DB1.0", String.valueOf(random.nextInt(20)));
        String res = this.s7PLC.readString("DB1.0");
        return ResponseEntity.ok(res);
    }
}

2. 序列化模式

添加S7序列化对象

package com.github.xingshuangs.s7.demo.config;


import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.serializer.S7Serializer;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xingshuang
 */
@Configuration
public class S7Config {

    @Bean
    public S7PLC s7PLC() {
        return new S7PLC(EPlcType.S1200, "127.0.0.1");
    }

    @Bean
    public S7Serializer s7Serializer(S7PLC s7PLC) {
        return new S7Serializer(s7PLC);
    }
}

添加数据采集类,添加注解配置

package com.github.xingshuangs.s7.demo.model;

import com.github.xingshuangs.iot.common.enums.EDataType;
import com.github.xingshuangs.iot.protocol.s7.serializer.S7Variable;
import lombok.Data;

/**
 * 测试对象
 *
 * @author xingshuang
 */
@Data
public class DemoBean {

    @S7Variable(address = "DB1.0.1", type = EDataType.BOOL)
    private boolean bitData;

    @S7Variable(address = "DB1.4", type = EDataType.UINT16)
    private int uint16Data;

    @S7Variable(address = "DB1.6", type = EDataType.INT16)
    private short int16Data;

    @S7Variable(address = "DB1.8", type = EDataType.UINT32)
    private long uint32Data;

    @S7Variable(address = "DB1.12", type = EDataType.INT32)
    private int int32Data;

    @S7Variable(address = "DB1.16", type = EDataType.FLOAT32)
    private float float32Data;

    @S7Variable(address = "DB1.20", type = EDataType.FLOAT64)
    private double float64Data;

    @S7Variable(address = "DB1.28", type = EDataType.BYTE, count = 3)
    private byte[] byteData;
}

添加控制层业务

package com.github.xingshuangs.s7.demo.controller;

import com.github.xingshuangs.iot.protocol.s7.serializer.S7Serializer;
import com.github.xingshuangs.s7.demo.model.DemoBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xingshuang
 */
@RestController
@RequestMapping("/serializer")
public class S7SerializerComController {

    @Autowired
    private S7Serializer s7Serializer;

    @GetMapping("/bean")
    public ResponseEntity<DemoBean> demoBean() {
        DemoBean bean = this.s7Serializer.read(DemoBean.class);
        return ResponseEntity.ok(bean);
    }
}
### 回答1: 西门子S7协议是德国西门子公司专为其S7系列可编程逻辑控制器(PLC)设备开发的一种通信协议。该协议用于实现PLC与上位机或其他设备之间的数据交换和控制命令传输。 Java是一种高级编程语言,具有跨平台、面向对象、易学易用等特点。Java语言拥有丰富的类库和API,可以方便地与各种硬件设备进行通信和交互。 针对西门子S7协议的Java开发,可以利用Java的网络编程能力,在与PLC建立网络连接后,采用S7协议进行数据传输和控制命令的发送与接收。Java中可以使用socket编程或使用第三方库来实现与PLC之间的通信,例如使用Java Socket类进行TCP/IP通信或使用Apache MINA等框架进行底层通信的封装。 在开发过程中,需要根据S7协议的规范和西门子提供的文档,了解S7协议的数据传输格式、通信建立过程、命令的编码与解码等细节。根据这些规范,使用Java编写相应的代码实现与PLC的通信,包括建立连接、读写数据、发送控制命令等操作。 总之,利用Java编程语言可以方便地实现对西门子S7协议的支持和应用开发,以实现PLC与上位机或其他设备之间的数据交换和控制命令传输。使用Java开发可以充分发挥其跨平台和强大的编程特性,提高开发效率和可移植性。 ### 回答2: 西门子S7协议是指用于西门子可编程逻辑控制器(PLC)的通信协议。它允许外部设备(如计算机或其他PLC)与S7系列PLC进行通信,实现数据传输和远程控制。而Java是一种面向对象的编程语言,具有跨平台、易于学习和使用等特点。 在使用Java进行西门子S7协议通信时,可以使用Java提供的Socket编程来实现与PLC之间的通信。Java的Socket类库提供了TCP/IP协议的支持,而西门子S7协议使用的就是TCP/IP协议进行通信。 首先,需要创建一个Socket对象连接到PLC的IP地址和端口号。然后,通过Socket对象的输入输出流发送和接收数据。使用西门子S7协议的命令格式来发送读写操作请求,以读取和写入PLC的数据。当收到PLC的响应后,可以解析响应数据并进行相应的处理。 除此之外,也可以使用Java相关的开源库,如Snap7,来简化与西门子S7协议通信的过程。Snap7是一个用C++编写的开源库,提供了用于连接和通信PLC的API接口。可以使用Java的JNI技术调用C++代码,在Java程序中使用Snap7库实现与PLC的通信。 总之,使用Java进行西门子S7协议通信需要借助Java的Socket编程或者结合开源库等方法来实现。这样可以实现与PLC的数据传输和远程控制,从而实现自动化控制系统中的各种功能。 ### 回答3: 西门子S7协议是西门子工业自动化领域中的一种通信协议,用于与S7系列PLC(可编程逻辑控制器)进行通信。该协议基于TCP/IP协议栈,可以在局域网或互联网上进行数据传输。 Java是一种面向对象编程语言,具有良好的跨平台性和易学性,在开发网络应用程序方面被广泛使用。 结合S7协议和Java,可以利用Java编写程序与S7 PLC进行通信和控制。首先,需要使用Java网络编程库建立与PLC的通信连接,可以使用Socket类建立TCP/IP连接。然后,通过S7协议的相关命令和指令,发送数据请求和接收响应,实现对PLC的监控和控制。 在Java中,可以使用第三方库如Snap7来实现与S7 PLC的通信。该库提供了一系列的Java API(应用程序接口),可以简化与PLC的通信操作。通过这些API,可以轻松地读取和写入PLC的存储器区域,获取实时数据,并发送控制指令。 通过Java编程和S7协议,可以实现远程监控和远程控制PLC系统。例如,可以监控PLC中各个传感器的数据并进行实时显示,或者发送指令控制各个执行器的运行状态。这为工业自动化系统的远程管理和监控提供了便利。 总之,利用Java编程和S7协议,可以实现与S7 PLC的通信和控制,达到远程监控和控制的目的。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值