Unity对接ModbusTCP
测试版本:unity2019.4.1和Unity2021.3.4均无问题
1、测试工具和dll文件链接:
链接:https://pan.baidu.com/s/1kLPesjtCJQOlT9Fq7qDEYA
提取码:rmug
2、导入NModbus4.dll文件到Unity的Plugins文件夹中
3、测试工具的使用
找到文件夹内ModSim32.exe程序,双击运行
弹出警告,点击确定
进入主界面点击File→New新建一个ModSim
当前未连接,所以会有NOT CONNECTEDI警告
根据需求选择对应连接模式
4、脚本
对应不同模式,使用不同方法
//using LitJson;
using Modbus.Device;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
/// <summary>
/// Modbus Tcp/IP
/// </summary>
public class Concent_ : MonoBehaviour
{
public ModbusMaster modbusIpMaster;
public TcpClient tcpClient;
IPAddress Address = new IPAddress(new byte[] { 127, 0, 0, 1 });
public int Port = 502;
public bool Conen = false;
public bool Reda_White;
private ushort[] Udata = new ushort[] { 0x03 };
private ushort star = 1;
Thread mythread;
public bool isconect = false;
ushort[] AoData11;
string ip;
private void Awake()
{
instance = this;
StartCoroutine(GetData());
}
void Start()
{
//Ip_.text = "127.0.0.1";//192.168.1.140
//Port_.text = "502";
OpenConnect_("127.0.0.1", 502);
//OpenConnect_(ip, 502);
}
// IEnumerator GetData()
// {
// var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "IP.json"));
// UnityWebRequest www = UnityWebRequest.Get(uri);
// yield return www.SendWebRequest();
// if (www.isNetworkError || www.isHttpError)
// {
// Debug.Log(www.error);
// }
// else
// {
// Debug.Log(www.downloadHandler.text);
// string jsonStr = www.downloadHandler.text;
// IPTest ques = JsonMapper.ToObject<IPTest>(jsonStr);
// ip = ques.ip;
// Debug.Log(ip);
// }
// }
public void OpenConnect_(string ip, int port)
{
if (Connect(ip, port))
{
Debug.Log("连接成功");
}
else
{
Debug.Log("连接失败"); }
}
public bool Connect(string ip, int port)
{
try
{
tcpClient = new TcpClient(ip, port);
tcpClient.SendTimeout = 1;
modbusIpMaster = ModbusIpMaster.CreateIp(tcpClient);
mythread = new Thread(WriteMessageFromClient);
mythread.Start();
Conen = true;
return true;
}
catch (Exception ex)
{
tcpClient.Close();
Debug.LogError(ex.Message);
return false;
}
}
public void WriteMessageFromClient()
{
while (Conen)
{
try
{
if (Reda_White)
{
Write_jiChunQi(star, Udata);
Debug.Log("发送成功");
}
if (kuse)
{
Debug.Log("a");
//READ HOLDING REGISTER
// 要从中读取值的设备地址(ModSim id) 开始阅读的地址(1~125) 要读取的保存寄存器的数目
ushort[] msg = modbusIpMaster.ReadHoldingRegisters(0x01, 0x01, 0x02);
}
}
catch
{
break;
}
}
tcpClient.Close();
}
public void Write_jiChunQi(ushort star, ushort[] data)
{
modbusIpMaster.WriteMultipleRegisters(1, star, data);
}
private byte GetHex(string msg)
{
byte hex = Convert.ToByte(msg);
return hex;
}
public int GetDexx(string msg)
{
int res = Convert.ToInt32(msg, 16);
return res;
}
private void OnApplicationQuit()
{
tcpClient.Close();
}
public bool kuse = false;
bool[] aa = new bool[] { true, false, true };
bool[] bool_coilstatus;
public ushort[] HoldingRegister;
public void BtnOnClick()
{
modbusIpMaster.WriteSingleCoil(0x01, 0, !zongkaiguan);
}
void FixedUpdate()
{
//if (Input.GetKeyDown(KeyCode.Alpha1))//第一个发送
//{
// modbusIpMaster.WriteSingleCoil(0x01, 0, false);//发送单个
// //modbusIpMaster.WriteMultipleCoils(0x01, 0, aa);//发送数组
// Debug.Log("发送成功");
//}
//if (Input.GetKeyDown(KeyCode.Alpha2))//第三个发送
//{
// //modbusIpMaster.WriteSingleRegister(0x01, 0, 7);//发送单个
// modbusIpMaster.WriteMultipleRegisters(0x01, 0, new ushort[] { 10, 2, 2 });//发送数组
// Debug.Log("发送成功");
//}
//if (Input.GetKeyDown(KeyCode.Alpha5))//第一个
//{
// bool_coilstatus = modbusIpMaster.ReadCoils(0x01, 0, 0x1);
// zongkaiguan = bool_coilstatus[0];
// foreach (var item in bool_coilstatus)
// {
// Debug.Log("读取到的数据:" + item);
// }
//}
//if (Input.GetKeyDown(KeyCode.Alpha6))//第二个
//{
// // modbusIpMaster.ReadInputRegistersAsync(0x01, 0, 0x5);
// //modbusIpMaster.ReadInputsAsync(0x01, 0, 0x5);
// s = modbusIpMaster.ReadInputs(0x01, 0, 0xe);
// foreach (var item in s)
// {
// Debug.Log("读取到的数据:" + item);
// }
//}
//if (Input.GetKeyDown(KeyCode.Alpha7))//第三个
//{
// HoldingRegister = modbusIpMaster.ReadHoldingRegisters(0x01, 0, 0x03);
// //string str = AoData.ToString();
// //Debug.Log(AoData.Length);
// foreach (var item in HoldingRegister)
// {
// Debug.Log("读取到的数据:" + item);
// }
//}
//if (Input.GetKeyDown(KeyCode.Alpha8))//第四个
//{
// ushort[] msg = modbusIpMaster.ReadInputRegisters(0x01, 0, 0x01);
// foreach (var item in msg)
// {
// Debug.Log(item);
// }
//}
}
}
public class IPTest
{
public string ip;
}