13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package com.ruoyi.fuzhou.utils.oilmodbus;
 
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.fuzhou.domain.ReceiveOilInfo;
import com.ruoyi.fuzhou.enums.DataTypeEnum;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
 
public class ModbusOilServerUtils {
    public static void main(String[] args) {
//
//        //质量流量
String value = getValue("0.0.0.0", 8140, (byte) 0x05, (byte) 0x04, 167, 0x0002,  1);
//        //利和油设备
//        String value = getValue("0.0.0.0", 8247, (byte) 1, (byte) 3, 13, 2, 12);
        System.out.println(value);
    }
    /**
     * @param ip   ip
     * @param port 端口
     * @param list 查询项列表
     */
    public static JSONObject getValue(String ip, int port, List<ReceiveOilInfo> list) {
        // 服务端配置
        String SERVER_IP = ip;  // 监听所有网络接口
        int SERVER_PORT = port;        // 端口号
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            System.out.println("🛡️ 服务端已启动,正在监听 " + SERVER_IP + ":" + SERVER_PORT + "...");
            serverSocket.setSoTimeout(4000);
            Socket clientSocket = serverSocket.accept();
            System.out.println("🔌 客户端已连接: " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream()) {
                JSONObject jsonObject = new JSONObject();
                for (ReceiveOilInfo info : list
                ) {
                    // 构造请求帧
                    ByteBuffer requestBuffer = ByteBuffer.allocate(8);
                    if (info.getDeviceAddress() != 0) {
                        requestBuffer.put(info.getDeviceAddress());  // 设备地址
                    }
                    if (info.getFunctionCode() != 0) {
                        requestBuffer.put(info.getFunctionCode());  // 功能码
                    }
                    if (info.getRegisterAdress() != 0) {
                        requestBuffer.putShort((short) info.getRegisterAdress().intValue());  // 寄存器地址
                    }
                    if (info.getRegisterCount() != 0) {
                        requestBuffer.putShort((short) info.getRegisterCount().intValue());  // 寄存器数量
                    }
                    // 计算CRC校验码
                    byte[] requestData = requestBuffer.array();
                    String hex = Crc16Utils.makeCRC(Crc16Utils.bytesToHex(requestData).substring(0, Crc16Utils.bytesToHex(requestData).length() - 4), true);
                    int decimal = Integer.parseInt(hex, 16);
                    requestBuffer.putShort((short) decimal);  // CRC校验码
                    // 发送请求帧
                    outputStream.write(requestBuffer.array());
                    System.out.println("📤 已发送 MODBUS 请求: " + bytesToHex(requestBuffer.array()));
                    // 接收设备响应
                    byte[] response = new byte[1024];
                    int bytesRead = inputStream.read(response);
                    if (bytesRead == -1) {
                        System.out.println("❌ 未收到设备响应");
                        continue;
                    }
                    // 打印响应数据
                    byte[] responseData = new byte[bytesRead];
                    System.arraycopy(response, 0, responseData, 0, bytesRead);
                    String resultData = bytesToHex(responseData);
                    System.out.println("📥 收到设备响应: " + resultData);
                    // 检查响应长度
                    if (responseData.length <= 5) {
                        System.out.println("❌ 无效的响应长度: " + responseData.length + " 字节");
                        continue;
                    }
                    //功能码
                    byte responseFunctionCode = responseData[1];
                    //数据字节数
                    byte byteCount = responseData[2];
                    byte[] data = new byte[byteCount];
                    System.arraycopy(responseData, 3, data, 0, byteCount);
                    byte[] crcReceived = new byte[2];
                    System.arraycopy(responseData, responseData.length - 2, crcReceived, 0, 2);
                    // 检查是否为错误响应(功能码 + 0x80)
                    if ((responseFunctionCode & 0x80) != 0) {
                        byte errorCode = responseData[2];  // 错误码
                        System.out.println("❌ 设备返回错误响应,错误码: " + errorCode);
                        continue;
                    }
                    if (DataTypeEnum.OIL.getCode().equals(info.getDataType())) {
                        byte[] bytes = ModbusFloatParserUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserUtil.parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.LIJIUOIL.getCode().equals(info.getDataType())) {
                        byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.LIJIUJUN.getCode().equals(info.getDataType())) {
                        byte[] bytes = ModbusFloatParserUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserUtil.parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.NIGDETUIYOU.getCode().equals(info.getDataType())) {
                        //todo 未做处理
                        byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    }
                }
                serverSocket.close();
                return jsonObject;
            } catch (Exception e) {
                System.out.println("⚠️ 客户端异常断开: " + e.getMessage());
            } finally {
                clientSocket.close();
            }
        } catch (Exception e) {
            if (serverSocket != null) {
                try {
                    System.out.println("油设备不在线" + e.getMessage());
                    serverSocket.close();
                } catch (Exception ex) {
                    System.out.println("❌ 油服务端关闭失败: " + ex.getMessage());
                }
            } else {
                System.out.println("❌ 油服务端启动失败: " + e.getMessage());
            }
        }
        return null;
    }
 
    /**
     * @param ip   ip
     * @param port 端口
     * @param list 查询项列表
     */
    public static JSONObject getLijiuValue(String ip, int port, List<ReceiveOilInfo> list) {
        // 服务端配置
        String SERVER_IP = ip;  // 监听所有网络接口
        int SERVER_PORT = port;        // 端口号
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            System.out.println("厦门利旧服务端已启动,正在监听 " + SERVER_IP + ":" + SERVER_PORT + "...");
            serverSocket.setSoTimeout(4000);
            Socket clientSocket = serverSocket.accept();
            System.out.println("厦门利旧客户端已连接: " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream()) {
                JSONObject jsonObject = new JSONObject();
                for (ReceiveOilInfo info : list
                ) {
                    // 构造请求帧
                    ByteBuffer requestBuffer = ByteBuffer.allocate(8);
                    if (info.getDeviceAddress() != 0) {
                        requestBuffer.put(info.getDeviceAddress());  // 设备地址
                    }
                    if (info.getFunctionCode() != 0) {
                        requestBuffer.put(info.getFunctionCode());  // 功能码
                    }
                    if (info.getRegisterAdress() != 0) {
                        requestBuffer.putShort((short) info.getRegisterAdress().intValue());  // 寄存器地址
                    }
                    if (info.getRegisterCount() != 0) {
                        requestBuffer.putShort((short) info.getRegisterCount().intValue());  // 寄存器数量
                    }
                    // 计算CRC校验码
                    byte[] requestData = requestBuffer.array();
                    String hex = Crc16Utils.makeCRC(Crc16Utils.bytesToHex(requestData).substring(0, Crc16Utils.bytesToHex(requestData).length() - 4), true);
                    int decimal = Integer.parseInt(hex, 16);
                    requestBuffer.putShort((short) decimal);  // CRC校验码
                    // 发送请求帧
                    outputStream.write(requestBuffer.array());
                    System.out.println("厦门利旧已发送 MODBUS 请求: " + bytesToHex(requestBuffer.array()));
                    // 接收设备响应
                    byte[] response = new byte[1024];
                    try {
                        Thread.sleep(5000);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    int bytesRead = inputStream.read(response);
                    if (bytesRead == -1) {
                        System.out.println("厦门利旧未收到设备响应");
                        continue;
                    }
                    // 打印响应数据
                    byte[] responseData = new byte[bytesRead];
                    System.arraycopy(response, 0, responseData, 0, bytesRead);
                    String resultData = bytesToHex(responseData);
                    System.out.println("厦门利旧收到设备响应: " + resultData);
                    // 检查响应长度
                    if (responseData.length <= 5) {
                        System.out.println("厦门利旧无效的响应长度: " + responseData.length + " 字节");
                        continue;
                    }
                    //功能码
                    byte responseFunctionCode = responseData[1];
                    //数据字节数
                    byte byteCount = responseData[2];
                    byte[] data = new byte[byteCount];
                    System.arraycopy(responseData, 3, data, 0, byteCount);
                    byte[] crcReceived = new byte[2];
                    System.arraycopy(responseData, responseData.length - 2, crcReceived, 0, 2);
                    // 检查是否为错误响应(功能码 + 0x80)
                    if ((responseFunctionCode & 0x80) != 0) {
                        byte errorCode = responseData[2];  // 错误码
                        System.out.println("厦门利旧设备返回错误响应,错误码: " + errorCode);
                        continue;
                    }
                    if (DataTypeEnum.OIL.getCode().equals(info.getDataType())) {
                        byte[] bytes = ModbusFloatParserUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserUtil.parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.LIJIUOIL.getCode().equals(info.getDataType())) {
                        byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.LIJIUJUN.getCode().equals(info.getDataType())) {
                        //todo 未做处理
                        byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                    } else if (DataTypeEnum.NIGDETUIYOU.getCode().equals(info.getDataType())) {
                        //todo 未做处理
                        byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                        byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                        // 解析为浮点数(大端字节顺序)
                        float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                        jsonObject.put(info.getParamCode(), String.valueOf(String.format("%.3f",floatValue)));
                        serverSocket.close();
                    }
                }
                return jsonObject;
            } catch (Exception e) {
                System.out.println("厦门利旧客户端异常断开: " + e.getMessage());
            } finally {
                clientSocket.close();
            }
        } catch (Exception e) {
            if (serverSocket != null) {
                try {
                    System.out.println("厦门利旧油设备不在线" + e.getMessage());
                    serverSocket.close();
                } catch (Exception ex) {
                    System.out.println("厦门利旧油服务端关闭失败: " + ex.getMessage());
                }
            } else {
                System.out.println("厦门利旧油服务端启动失败: " + e.getMessage());
            }
        }
        return null;
    }
 
    /**
     * @param ip              ip
     * @param port            端口
     * @param address         地址码
     * @param functionCode    功能码
     * @param registerAddress 寄存器地址
     * @param registerCount   寄存器数量
     * @param dataType        结果数据类型
     */
    public static String getValue(String ip, int port, byte address, byte functionCode, int registerAddress, int registerCount, int dataType) {
        // 服务端配置
        String SERVER_IP = ip;  // 监听所有网络接口
        int SERVER_PORT = port;        // 端口号
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            System.out.println("🛡️ 服务端已启动,正在监听 " + SERVER_IP + ":" + SERVER_PORT + "...");
            serverSocket.setSoTimeout(8000);
            Socket clientSocket = serverSocket.accept();
            System.out.println("🔌 客户端已连接: " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
            try (InputStream inputStream = clientSocket.getInputStream();
                 OutputStream outputStream = clientSocket.getOutputStream()) {
                // 构造请求帧
                ByteBuffer requestBuffer = ByteBuffer.allocate(8);
                if (address != 0) {
                    requestBuffer.put(address);  // 设备地址
                }
                if (functionCode != 0) {
                    requestBuffer.put(functionCode);  // 功能码
                }
                if (registerAddress != 0) {
                    requestBuffer.putShort((short) registerAddress);  // 寄存器地址
                }
                if (registerCount != 0) {
                    requestBuffer.putShort((short) registerCount);  // 寄存器数量
                }
                // 计算CRC校验码
                byte[] requestData = requestBuffer.array();
                String hex = Crc16Utils.makeCRC(Crc16Utils.bytesToHex(requestData).substring(0, Crc16Utils.bytesToHex(requestData).length() - 4), true);
                int decimal = Integer.parseInt(hex, 16);
                requestBuffer.putShort((short) decimal);  // CRC校验码
                // 发送请求帧
                outputStream.write(requestBuffer.array());
                System.out.println("📤 已发送 MODBUS 请求: " + bytesToHex(requestBuffer.array()));
                // 接收设备响应
                byte[] response = new byte[1024];
                try {
                    Thread.sleep(3000);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                int bytesRead = inputStream.read(response);
                if (bytesRead == -1) {
                    System.out.println("❌ 未收到设备响应");
                    return null;
                }
                // 打印响应数据
                byte[] responseData = new byte[bytesRead];
                System.arraycopy(response, 0, responseData, 0, bytesRead);
                String resultData = bytesToHex(responseData);
                System.out.println("📥 收到设备响应: " + resultData);
                // 检查响应长度
                if (responseData.length <= 5) {
                    System.out.println("❌ 无效的响应长度: " + responseData.length + " 字节");
                    return null;
                }
                //功能码
                byte responseFunctionCode = responseData[1];
                //数据字节数
                byte byteCount = responseData[2];
                byte[] data = new byte[byteCount];
                System.arraycopy(responseData, 3, data, 0, byteCount);
                byte[] crcReceived = new byte[2];
                System.arraycopy(responseData, responseData.length - 2, crcReceived, 0, 2);
                // 检查是否为错误响应(功能码 + 0x80)
                if ((responseFunctionCode & 0x80) != 0) {
                    byte errorCode = responseData[2];  // 错误码
                    System.out.println("❌ 设备返回错误响应,错误码: " + errorCode);
                    return null;
                }
                if (DataTypeEnum.OIL.getCode().equals(dataType)) {
                    byte[] bytes = ModbusFloatParserUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                    // 解析为浮点数(大端字节顺序)
                    float floatValue = ModbusFloatParserUtil.parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
                    return String.valueOf(floatValue);
                } else if (DataTypeEnum.LIJIUOIL.getCode().equals(dataType)) {
                    byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                    byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                    // 解析为浮点数(大端字节顺序)
                    float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                    return String.valueOf(floatValue);
                } else if (DataTypeEnum.LIJIUJUN.getCode().equals(dataType)) {
                    byte[] bytes = ModbusFloatParserUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                    // 解析为浮点数(大端字节顺序)
                    float floatValue = ModbusFloatParserUtil.parseAsFloat(bytes, ByteOrder.BIG_ENDIAN);
                    return String.valueOf(floatValue);
                } else if (DataTypeEnum.NIGDETUIYOU.getCode().equals(dataType)) {
                    //todo 未做处理
                    byte[] bytes = ModbusFloatParserLittleUtil.hexStringToByteArray(resultData.substring(6, 6 + byteCount * 2));
                    byte[] reorderedBytes = ModbusFloatParserLittleUtil.reorderBytesForFloat(bytes);
                    // 解析为浮点数(大端字节顺序)
                    float floatValue = ModbusFloatParserLittleUtil.parseAsFloat(reorderedBytes, ByteOrder.BIG_ENDIAN);
                    return String.valueOf(floatValue);
                }
            } catch (IOException e) {
                System.out.println("⚠️ 客户端异常断开: " + e.getMessage());
            } finally {
                clientSocket.close();
            }
        } catch (IOException e) {
            if (serverSocket != null) {
                try {
                    System.out.println("设备不在线" + e.getMessage());
                    serverSocket.close();
                } catch (IOException ex) {
                    System.out.println("❌ 服务端关闭失败: " + ex.getMessage());
                }
            } else {
                System.out.println("❌ 服务端启动失败: " + e.getMessage());
            }
        }
        return null;
    }
 
    // 将字节数组转换为十六进制字符串
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
 
    // CRC16 计算
    public static int crc16(byte[] data) {
        int crc = 0xFFFF;
        for (byte b : data) {
            crc ^= (b & 0xFF);
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        return crc;
    }
}