GithubHelp home page GithubHelp logo

zhaopeiym / iotclient Goto Github PK

View Code? Open in Web Editor NEW
1.1K 37.0 378.0 482 KB

This is an IoT device communication protocol implementation client, which will include common industrial communication protocols such as mainstream PLC communication reading, ModBus protocol, and Bacnet protocol. This component is open source and free for life, using the most relaxed MIT open source agreement, you can modify and commercial use at will (commercial use please evaluate and test). 这是一个物联网设备通讯协议实现客户端,将会包括主流PLC通信读取、ModBus协议、Bacnet协议等常用工业通讯协议。本组件终身开源免费,采用最宽松的MIT开源协议,您可以随意修改和商业使用(商业使用请做好评估和测试)。

License: MIT License

C# 100.00%
iot iotclient tcp socket modbustcp modbusrtu modbusascii plc bacnet siemens siemens-s7 siemens-plc modbus plc-modbus-bacnet mitsubishi mitsubishi-plc omron-plc omronfins omron

iotclient's Introduction

IoTClient

English | 中文文档

image image image

  • This is an IoT device communication protocol realization client, which will include mainstream PLC communication reading, ModBus protocol, Bacnet protocol and other common industrial communication protocols.
  • This component is based on .NET Standard 2.0 and can be used for cross-platform development of .Net, such as Windows, Linux and even run on Raspberry Pi.
  • This component is open source and free for life, and adopts the most relaxed MIT protocol. You can also modify and use it for commercial use (commercial use please evaluate and test).
  • Development tools:Visual Studio 2019
  • QQ exchange group:700324594

Document directory

Instructions for use

Reference component

Nuget installation Install-Package IoTClient
Or graphical installation
image

ModBusTcp read and write operations

//1、Instantiate the client-enter the correct IP and port
ModBusTcpClient client = new ModBusTcpClient("127.0.0.1", 502);

//2、Write operation-parameters are: address, value, station number, function code
client.Write("4", (short)33, 2, 16);

//2.1、[Note] When writing data, you need to clarify the data type
client.Write("0", (short)33, 2, 16);    //Write short type value
client.Write("4", (ushort)33, 2, 16);   //Write ushort type value
client.Write("8", (int)33, 2, 16);      //Write int type value
client.Write("12", (uint)33, 2, 16);    //Write uint type value
client.Write("16", (long)33, 2, 16);    //Write long type value
client.Write("20", (ulong)33, 2, 16);   //Write ulong type value
client.Write("24", (float)33, 2, 16);   //Write float type value
client.Write("28", (double)33, 2, 16);  //Write double type value
client.Write("32", true, 2, 5);         //Write Coil type value
client.Write("100", "orderCode", stationNumber);  //Write string

//3、Read operation-the parameters are: address, station number, function code
var value = client.ReadInt16("4", 2, 3).Value;

//3.1、Other types of data reading
client.ReadInt16("0", stationNumber, 3);    //short type data read
client.ReadUInt16("4", stationNumber, 3);   //ushort type data read
client.ReadInt32("8", stationNumber, 3);    //int type data read
client.ReadUInt32("12", stationNumber, 3);  //uint type data read
client.ReadInt64("16", stationNumber, 3);   //long type data read
client.ReadUInt64("20", stationNumber, 3);  //ulong type data read
client.ReadFloat("24", stationNumber, 3);   //float type data read
client.ReadDouble("28", stationNumber, 3);  //double type data read
client.ReadCoil("32", stationNumber, 1);    //Coil type data read
client.ReadDiscrete("32", stationNumber, 2);//Discrete type data read
client.ReadString("100", stationNumber,readLength:10); //Read string

//4、If there is no active Open, it will automatically open and close the connection every time you read and write operations, which will greatly reduce the efficiency of reading and writing. So it is recommended to open and close manually.
client.Open();

//5、Read and write operations will return the operation result object Result
var result = client.ReadInt16("4", 2, 3);
//5.1 Whether the reading is successful (true or false)
var isSucceed = result.IsSucceed;
//5.2 Exception information for failed reading
var errMsg = result.Err;
//5.3 Read the request message actually sent by the operation
var requst  = result.Requst;
//5.4 Read the response message from the server
var response = result.Response;
//5.5 Read value
var value3 = result.Value;

//6、Batch read
var list = new List<ModBusInput>();
list.Add(new ModBusInput()
{
    Address = "2",
    DataType = DataTypeEnum.Int16,
    FunctionCode = 3,
    StationNumber = 1
});
list.Add(new ModBusInput()
{
    Address = "2",
    DataType = DataTypeEnum.Int16,
    FunctionCode = 4,
    StationNumber = 1
});
list.Add(new ModBusInput()
{
    Address = "199",
    DataType = DataTypeEnum.Int16,
    FunctionCode = 3,
    StationNumber = 1
});
var result = client.BatchRead(list);

//7、Other parameters of the constructor
//IP, port, timeout time, big and small end settings
ModBusTcpClient client = new ModBusTcpClient("127.0.0.1", 502, 1500, EndianFormat.ABCD);

For more usage of ModBusTcp, please refer to Unit Test

ModBusRtu read and write operations

//Instantiate the client-[COM port name, baud rate, data bits, stop bits, parity]
ModBusRtuClient client = new ModBusRtuClient("COM3", 9600, 8, StopBits.One, Parity.None);

//Other read and write operations are the same as ModBusTcpClient's read and write operations

ModBusAscii read and write operations

//Instantiate the client-[COM port name, baud rate, data bits, stop bits, parity]
ModbusAsciiClient client = new ModbusAsciiClient("COM3", 9600, 8, StopBits.One, Parity.None);

//Other read and write operations are the same as ModBusTcpClient's read and write operations

ModbusRtuOverTcp read and write operations

//Serial port transparent transmission i.e.: send Rtu format messages in Tcp mode

//Instantiate the client-IP, port, timeout, big and small end settings
ModbusRtuOverTcpClient client = new ModbusRtuOverTcpClient("127.0.0.1", 502, 1500, EndianFormat.ABCD);

//Other read and write operations are the same as ModBusTcpClient's read and write operations

SiemensClient (Siemens) read and write operations

//1、Instantiate the client-enter the model, IP and port
//Other models:SiemensVersion.S7_200、SiemensVersion.S7_300、SiemensVersion.S7_400、SiemensVersion.S7_1200、SiemensVersion.S7_1500
SiemensClient client = new SiemensClient(SiemensVersion.S7_200Smart, "127.0.0.1",102);

//2、Write operation
client.Write("Q1.3", true);
client.Write("V2205", (short)11);
client.Write("V2209", 33);

//3、Read operation
var value1 = client.ReadBoolean("Q1.3").Value;
var value2 = client.ReadInt16("V2205").Value;
var value3 = client.ReadInt32("V2209").Value;

//4、If there is no active Open, it will automatically open and close the connection every time you read and write operations, which will greatly reduce the efficiency of reading and writing. So it is recommended to open and close manually.
client.Open();

//5、Read and write operations will return the operation result object Result
var result = client.ReadInt16("V2205");
//5.1 Whether the reading is successful (true or false)
var isSucceed = result.IsSucceed;
//5.2 Exception information for failed reading
var errMsg = result.Err;
//5.3 Read the request message actually sent by the operation
var requst  = result.Requst;
//5.4 Read the response message from the server
var response = result.Response;
//5.5 Read value
var value4 = result.Value;

Note: About Siemens PLC address

VB263、VW263、VD263中的B、W、D分别表示:byte型(8位)、word型(16位)、doubleword型(32位)。

When this component passes in the address, there is no need to carry the data type, just use the corresponding method to read the corresponding type, such as:
VB263       - client.ReadByte("V263")
VD263       - client.ReadFloat("V263")
VD263       - client.ReadInt32("V263")
DB108.DBW4  - client.ReadUInt16("DB108.4")
DB1.DBX0.0  - client.ReadBoolean("DB1.0.0")
DB1.DBD0    - client.ReadFloat("DB1.0")
C# data type smart200 1200/1500/300
bit V1.0 DB1.DBX1.0
byte VB1 DB1.DBB1
shor
ushort
VW2 DB1.DBW2
int
uint
float
VD4 DB1.DBD4

SiemensClient best practices

1、When not to take the initiative to open
Siemens plc generally allows up to 8 long connections. So when the number of connections is not enough or when doing testing, do not take the initiative to open, so that the component will automatically open and close immediately.

2、When to take the initiative to open
When the number of long connections is enough, and you want to improve the read and write performance.

3、In addition to active Open connections, batch read and write can also greatly improve read and write performance.
//Batch read
Dictionary<string, DataTypeEnum> addresses = new Dictionary<string, DataTypeEnum>();
addresses.Add("DB4.24", DataTypeEnum.Float);
addresses.Add("DB1.434.0", DataTypeEnum.Bool);
addresses.Add("V4109", DataTypeEnum.Byte);
...
var result = client.BatchRead(addresses);

//Batch write
Dictionary<string, object> addresses = new Dictionary<string, object>();
addresses.Add("DB4.24", (float)1);
addresses.Add("DB4.0", (float)2);
addresses.Add("DB1.434.0", true);
...
var result = client.BatchWrite(addresses);

4、[Note] When writing data, you need to clarify the data type
client.Write("DB4.12", 9);          //What is written is of type int
client.Write("DB4.12", (float)9);   //What is written is a float type

5、SiemensClient is a thread safe class
Due to limited long PLC connections, SiemensClient is designed as a thread-safe class. You can set SiemensClient as a singleton, and use the instance of SiemensClient to read and write PLC between multiple threads.

MitsubishiClient (Mitsubishi) read and write operations

//1、Instantiate the client-enter the correct IP and port
MitsubishiClient client = new MitsubishiClient(MitsubishiVersion.Qna_3E, "127.0.0.1",6000);

//2、Write operation
client.Write("M100", true);
client.Write("D200", (short)11);
client.Write("D210", 33);

//3、Read operation
var value1 = client.ReadBoolean("M100").Value;
var value2 = client.ReadInt16("D200").Value;
var value3 = client.ReadInt32("D210").Value;

//4、If there is no active Open, it will automatically open and close the connection every time you read and write operations, which will greatly reduce the efficiency of reading and writing. So it is recommended to open and close manually.
client.Open();

//5、Read and write operations will return the operation result object Result
var result = client.ReadInt16("D210");
//5.1 Whether the reading is successful (true or false)
var isSucceed = result.IsSucceed;
//5.2 Exception information for failed reading
var errMsg = result.Err;
//5.3 Read the request message actually sent by the operation
var requst  = result.Requst;
//5.4 Read the response message from the server
var response = result.Response;
//5.5 Read value
var value4 = result.Value;

OmronFinsClient (Omron) read and write operations

//1、Instantiate the client-enter the correct IP and port
OmronFinsClient client = new OmronFinsClient("127.0.0.1",6000);

//2、Write operation
client.Write("M100", true);
client.Write("D200", (short)11);
client.Write("D210", 33);

//3、Read operation
var value1 = client.ReadBoolean("M100").Value;
var value2 = client.ReadInt16("D200").Value;
var value3 = client.ReadInt32("D210").Value;

//4、If there is no active Open, it will automatically open and close the connection every time you read and write operations, which will greatly reduce the efficiency of reading and writing. So it is recommended to open and close manually.
client.Open();

//5、Read and write operations will return the operation result object Result
var result = client.ReadInt16("D210");
//5.1 Whether the reading is successful (true or false)
var isSucceed = result.IsSucceed;
//5.2 Exception information for failed reading
var errMsg = result.Err;
//5.3 Read the request message actually sent by the operation
var requst  = result.Requst;
//5.4 Read the response message from the server
var response = result.Response;
//5.5 Read value
var value4 = result.Value;

AllenBradleyClient read and write operations

//1、Instantiate the client-enter the correct IP and port
AllenBradleyClient client = new AllenBradleyClient("127.0.0.1",44818);

//2、Write operation 
client.Write("A1", (short)11); 

//3、Read operation
var value = client.ReadInt16("A1").Value;

//4、If there is no active Open, it will automatically open and close the connection every time you read and write operations, which will greatly reduce the efficiency of reading and writing. So it is recommended to open and close manually.
client.Open();

//5、Read and write operations will return the operation result object Result
var result = client.ReadInt16("A1");
//5.1 Whether the reading is successful (true or false)
var isSucceed = result.IsSucceed;
//5.2 Exception information for failed reading
var errMsg = result.Err;
//5.3 Read the request message actually sent by the operation
var requst  = result.Requst;
//5.4 Read the response message from the server
var response = result.Response;
//5.5 Read value
var value4 = result.Value;

Some projects based on IoTClient library

IoTClient Tool Desktop program tool (open source)

IoTClient Tool 桌面程序工具,开源地址

  • 1、可用来测试PLC和相关协议的通信
  • 2、可作为IoTClient库使用例子。

image

image

image

image

image

image

image

image

image

image

Energy Management System (Commercial)

能源管理-现场-单项目

image
image

能源管理-云端-多项目

image
image
image
image
image
image
image

能源管理-移动端

imageimageimageimageimageimageimage

Haidilao terminal control (commercial)

海底捞末端控制-web

image
image
image
image

海底捞末端控制-移动端

imageimageimageimage

iotclient's People

Contributors

zhaopeiym avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iotclient's Issues

在TCPserver没有应答的情况下socketTcp重连异常,导致致命性错误

OtherControl,114行

private void but_tcpSend_Click(object sender, EventArgs e)
        {
            try
            {
                var command = DataConvert.StringToByteArray(txt_tcpmsg.Text, false);
                socketTcp.Send(command);
                var msg = SocketRead(socketTcp, 4096);
                AppendText(msg.ByteArrayToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //重新连接
                socketTcp?.Close();
                socketTcp.Connect(new IPEndPoint(IPAddress.Parse(txt_tcpip.Text?.Trim()), int.Parse(txt_tcpport.Text?.Trim())));
            }
        }

应该再包一层try 或者用非阻塞的方式Receive

如何读取三菱PLC的字符串

95dbab06baf2e666b26f72de9d30c69

你的代码中这个方法没有实现,那么我如何可以读取到字符串呢
public Result ReadString(string address)
{
throw new NotImplementedException();
}

AllenBradley Error reading variables with dot

Hello,

It´s there some way to read/write variables with dot in the name ?.
For example a bool variable called HMI.TEST
And also when the scope of the variable is different of the main.
For example ( MainProgram:ALARMS )

Thanks in advance

SiemensClient.BatchWrite 写入失败

SiemensClient

Dictionary<string, object> arr = new Dictionary<string, object>();
arr.Add("va01", 8);
arr.Add("va02", 0.5);
arr.Add("va03", 2.9);
arr.Add("va04", true);
arr.Add("va05", (byte)1);
var result = client.BatchWrite(arr,5);

一直提示result.IsSucceed==false
单个写入没有问题。
请指点。。。

请问此程序支持三菱FX3u不?

FX32能够连接成功,但是读写数据出错,我尝试使用Version.None也不可用。
不管是读取M0 Boolean变量,还是D0的word变量
image

读写西门子PLC信号异常

在我打开我的程序连接到模拟服务后,我给某个信号写short值1,我软件接收到这个信号开始操作,第一次读的时候,我判断有复位标志写入short值为0,成功执行了,后面我在没有给这个信号写1的情况下,我再次读取该信号,莫名的给我自动写1,使得我的程序一直循环执行里面的功能,版本为1.0.9

ModbusTcpClient连接状态

如何判断ModbusTcpClient的连接状态,ModbusTcpClient对象没有类似于Connected这样的状态属性

关于ABPLC读取的问题请教

在读取AB PLC 时
AllenBradleyClient client = new AllenBradleyClient("192.168.3.16", 44818);
IoTClient.Result result1 = client.ReadUInt32("ST_L82Edata");
这个ST_L82Edata是一个长度为100的数组,我用ReadUInt32的方法只能读取到他的第一位,我可以尝试用什么方法读取全部数组呢?
thanks

Will this work with Mitsubishi - model no : Q10UDEHCPU

I am trying to fetch value from D1002 kindly refer the attached screenshot

address

Will the below code do the job.

MitsubishiClient client = new MitsubishiClient(MitsubishiVersion.Qna_3E, "127.0.0.1",6000);
var value3 = client.ReadInt32("D1002").Value;

Note: I know the correct ip and port number.

功能建议

我遇到的问题是使用RS485设备链接ModbusRTU协议的设备,收到的数据头和尾分别多了一个0,导致CRC校验失败。
我修改了您的代码,在SerialPortBase类中的SerialPortRead方法末尾添加了过滤首尾00,建议您增加这个小功能

S400 插槽号问题

image
image
大神早上好,今天遇到一个问题,连接时IOTClient Tool提示连接被断开。用另外一款测试工具试了一下,里面可以修改插槽号,把插槽号改成2就正常连接了。咱们这个可以配置插槽号吗?

西门子解析地址异常

地址[DB400.DBX1.6]解析异常,ConvertArg Err:输入字符串的格式不正确。
大神晚上好,我是直接用的西门子客户端,类似DB400.DBX1.6这样的地址都会报错
image

怎么样捕获异常

读写地址有问题怎么样捕获异常。result.err是自己取。
或者有异常自动写入日志文件的功能吗

SerialPortBase.SerialPortRead读取数据出现问题

问题描述:使用过程中有些硬件设备读取不到数据或数据不完整
可能会出现“判断超时的循环”直接跳过的情况猜测:
1、var tempBufferLength = serialPort.BytesToRead;与tempBufferLength != serialPort.BytesToRead判断中间没有等待时间,serialPort.BytesToRead != 0使,很可能直接略过循环,使得数据读取不完整
2、Thread.Sleep(20);这个等待时间很短,也有可能导致bytesToRead != serialPort.BytesToRead这个判断不成立直接跳出循环的情况,使得数据读取不完整
3、建议var tempBufferLength = serialPort.BytesToRead;改为var tempBufferLength = 0; 并且延时处理的时间加长一些
对应源码:
protected Result<byte[]> SerialPortRead(SerialPort serialPort) { Result<byte[]> result = new Result<byte[]>(); DateTime beginTime = DateTime.Now; var tempBufferLength = serialPort.BytesToRead; //在(没有取到数据或BytesToRead在继续读取)且没有超时的情况,延时处理 while ((serialPort.BytesToRead == 0 || tempBufferLength != serialPort.BytesToRead) && DateTime.Now - beginTime <= TimeSpan.FromMilliseconds(serialPort.ReadTimeout)) { tempBufferLength = serialPort.BytesToRead; //延时处理 Thread.Sleep(20); } byte[] buffer = new byte[serialPort.BytesToRead]; var receiveFinish = 0; while (receiveFinish < buffer.Length) { var readLeng = serialPort.Read(buffer, receiveFinish, buffer.Length); if (readLeng == 0) { result.Value = null; return result.EndTime(); } receiveFinish += readLeng; } result.Value = buffer; return result.EndTime(); }

西门子S7_1200 批量读取异常问题

image
image
image
image
大神,西门子S7_1200 批量读取时,批量读取数量设置为2时正常,超过3,比如设置4,12,15就不正常了,15的时候很多数字变成了科学计数法形式

西门子S7_1200 批量读取异常问题

image
image
image
image
大神,西门子S7_1200 批量读取时,批量读取数量设置为2时正常,超过3,比如设置4,12,15就不正常了,15的时候很多数字变成了科学计数法形式

ABPlc批量读写是否异常

在AllenBradleyClient.cs文件中
public Result<byte[]> Read(string address, ushort length, bool isBit = false, bool setEndian = true)
{
....
var command = GetReadCommand(address, 1);
....
}
这个1是否应该未length才合适????

SendPackage错误

当functionCode=2,会计算出一个readLenght=13,但实际设备返回的可长度可能小于13,比如我用的的设备返回的只有长度只有6,这会导致在SocketTryRead中的while循环时,第一次已经把所有buffer读回来了,结果也是正确的,但因为判定长度小于13会再次读取,然后再下次循环中进行 socket.Receive时就报错了,应该在Recevie之前判断一下socket.Available?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.