H_SafeExperienceDrivingSystem/U3D_DrivingSystem/Assets/Script/ModbusTcpClient.cs

114 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using UnityEngine;
public class ModbusTcpClient
{
private TcpClient tcpClient;
private string serverIp = "127.0.0.1";
private int serverPort = 12315;
public ModbusTcpClient()
{
tcpClient = new TcpClient();
}
public async Task ConnectToServer()
{
try
{
await tcpClient.ConnectAsync(serverIp, serverPort);
Debug.Log("Connected to Modbus server.");
await SendModbusRequest();
}
catch (Exception ex)
{
Debug.Log("Error connecting to Modbus server: " + ex.Message);
}
}
private async Task SendModbusRequest()
{
byte[] request = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x10 };
NetworkStream stream = tcpClient.GetStream();
if (stream.CanWrite)
{
await stream.WriteAsync(request, 0, request.Length);
Debug.Log("Modbus request sent.");
await ReadResponse(stream);
}
}
private async Task ReadResponse(NetworkStream stream)
{
byte[] response = new byte[256];
int bytesRead = await stream.ReadAsync(response, 0, response.Length);
Debug.Log("Received response from Modbus server.");
if (bytesRead > 9) // 确保响应长度足够
{
// 解析响应数据
int length = response[5]; // 获取数据长度
byte deviceId = response[6]; // 设备编号
byte functionCode = response[7]; // 功能码
Debug.Log($"Device ID: {deviceId}, Function Code: {functionCode}, Data Length: {length}");
// 从第9个字节开始每两个字节解析一个数据
for (int i = 9; i < 9 + length; i += 2)
{
ushort dataValue = (ushort)(response[i] << 8 | response[i + 1]);
switch ((i - 9) / 2)
{
case 0: // 钥匙开关数据
Debug.Log($"Key Switch Data: {dataValue}");
break;
case 1: // 方向盘数据
Debug.Log($"Steering Wheel Data: {dataValue}");
break;
case 2: // 方向盘上喇叭状态
Debug.Log($"Horn Status: {dataValue}");
break;
case 3: // 刹车踏板数据
Debug.Log($"Brake Pedal Data: {dataValue}");
break;
case 4: // 油门踏板数据
Debug.Log($"Throttle Pedal Data: {dataValue}");
break;
case 5: // 离合踏板数据
Debug.Log($"Clutch Pedal Data: {dataValue}");
break;
case 6: // 手刹数据
Debug.Log($"Handbrake Data: {dataValue}");
break;
// 其他预留数据的解析
default:
Debug.Log($"Reserved Data {i/2 - 4}: {dataValue}");
break;
}
}
}
else
{
Debug.Log("Invalid response length.");
}
}
public void CloseConnection()
{
if (tcpClient != null)
{
if (tcpClient.Connected)
{
tcpClient.GetStream().Close();
tcpClient.Close();
Debug.Log("Connection to Modbus server closed.");
}
}
}
}