You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lxCameraApi/src/main/java/com/example/lxcameraapi/S7WriteTest.java

96 lines
3.0 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.example.lxcameraapi;
import com.sourceforge.snap7.moka7.S7;
import com.sourceforge.snap7.moka7.S7Client;
import java.time.LocalDateTime;
/**
* S7 PLC 数据写入测试工具
*/
public class S7WriteTest {
// PLC连接参数
private static final String IP = "127.0.0.1";
private static final int RACK = 0;
private static final int SLOT = 2;
private static final int DB_NUMBER = 1;
public static void main(String[] args) {
S7Client client = new S7Client();
try {
// 连接PLC
int result = client.ConnectTo(IP, RACK, SLOT);
if (result != 0) {
System.out.println("连接PLC失败错误码: " + result);
return;
}
System.out.println("连接PLC成功");
// 写入数据
writePlcData(client);
System.out.println("写入完成");
} catch (Exception e) {
System.out.println("异常: " + e.getMessage());
e.printStackTrace();
} finally {
client.Disconnect();
}
}
private static void writePlcData(S7Client client) {
byte[] buffer = new byte[100];
LocalDateTime now = LocalDateTime.now();
String date = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 托盘号 String[50] (偏移0长度52字节含2字节长度前缀)
writeS7String(buffer, 0, 50, "TRAY-20260427-"+date);
// 批次号 String[20] (偏移52长度22字节)
writeS7String(buffer, 52, 20, "BATCH-ABC123");
// 日期 String[20] (偏移74长度22字节)
writeS7String(buffer, 74, 20, "2026-04-27 10:30:00");
// 拍照标志 byte (偏移96)
buffer[96] = 1;
// 拍照结果 byte (偏移97)
buffer[97] = 0;
// 写入PLC (从偏移0开始写入98字节)
int writeResult = client.WriteArea(S7.S7AreaDB, DB_NUMBER, 0, buffer.length, buffer);
if (writeResult == 0) {
System.out.println("写入成功");
} else {
System.out.println("写入失败,错误码: " + writeResult);
}
}
/**
* 写入S7 String格式
* @param buffer 目标缓冲区
* @param offset 偏移量
* @param maxLen 最大长度
* @param value 要写入的字符串
*/
private static void writeS7String(byte[] buffer, int offset, int maxLen, String value) {
// S7 String格式: [0]=最大长度, [1]=实际长度, [2+]=字符串内容
buffer[offset] = (byte) maxLen;
byte[] valueBytes = value.getBytes();
byte actualLen = (byte) Math.min(valueBytes.length, maxLen);
buffer[offset + 1] = actualLen;
// 复制字符串内容
for (int i = 0; i < actualLen; i++) {
buffer[offset + 2 + i] = valueBytes[i];
}
// 剩余部分填充空格
for (int i = actualLen; i < maxLen; i++) {
buffer[offset + 2 + i] = ' ';
}
}
}