C # read Modbus data

Source: Internet
Author: User

In front of the continuous writing about the socket programming things, it seems a bit tall on, in order to learn and learn. So here we come to the point of practical application of something. C # How to read Modbus data, Modbus Many people may not know, also normal, interlacing as Foster. Modbus in the automation industry is not the same, belongs to the no secret of things, a lot of equipment, procedures are closely related to Modbus.

Modbus this thing, I am also a two knife, only half a bottle of water, so sloshing here, write some modbus things, but also let oneself understand a bit deeper, the entry level of things, hoping to help those like some do not know the Modbus, but want to know about Modbus comrade. As for the master, can spit groove, of course, can also be bypassed.

Modbus communication protocol, Modbus Network is an industrial communication system, by the intelligent terminalProgrammable ControllerAnd the computer is connected by a public line or a local dedicated line. ItsSystem StructureIncluding hardware, also includesSoftware。 It can be applied to a variety of data acquisition and process monitoring.

Modbus protocol is a common language applied to electronic controllers. With this protocol, controllers can communicate between each other, the controller through the network (for example, Ethernet) and other devices. It has become a general industry standard. With it, the control equipment produced by different manufacturers can be connected to an industrial network for centralized monitoring ...

These are Baidu come, hehe, don't spit groove. A lot of information on the Internet, interested can be their own, see more feel like all the same. A language that a person deems to communicate between a communication protocol, a machine, or a device. We communicate with people do not have language or text, the machine can of course send each other information, as long as the rules can be set.     Modbus is the language used to communicate with automation equipment. About Modbus for our programming people, we can greatly reduce the scope of understanding, we only need to care about the coding has something to do with what the hardware of those pins, cables, signal bits are not too concerned about, of course, if you want to become a modbus experts, it is different.Modbus is divided into two modes, a serial port mode, a TCP/IP mode. The serial port mode feels less and more, and now most of them are TCP/IP mode, so here we write TCP/IP temporarilyThe first thing to do is to get the socket client to establish a connection with the device, because the previous socket we have written, then the code below is very easy. Say simple point, you do not think is what Modbus, think is a computer, opened the socket service here. So the following code will follow.    
public bool Open (string Ip,int port) {            try {                tcpClient = new TcpClient ();                Tcpclient.connect (Ipaddress.parse (IP), port);                return true;            } catch (SocketException e) {                string m = string. Format ("Modbus Client Server connection error: {0},ip:{1},port:{2}", E.message, IP, port);                Loghelper.writelog (m);                return false;            }        }
Where the Loghelper code is not written here, because it has nothing to do with the topic, if you want to run the above code, comments on the line, I personally recommend that the code is not necessary to run a bit, see to understand the line. To run this thing, something will delay too much time. Here the IP and port numbers are provided by the device side.       The real program typically writes these two parameters to the configuration file. After the device is connected, the next step of course is to read the data. The basic principle of Modbus is that the program requests to the device, which data needs to be read, and the device returns the corresponding data. We know that machines, or computers, only know 01001 of these strings. So the so-called Modbus protocol, to put it simply, is to specify what the meaning of such a 0101 character each represents.
<summary>///Read data Modbus///</summary>//<param name= "RData" > Results &LT;/PARAM&G        T <param name= "id" > Device number </param>//<param name= "Address" > Device address </param>//<para M name= "len" > Length-how many devices </param>//<returns> Data read results are successful </returns> public bool Receivedat A (ref short[] RData, short ID, short address, short Len) {try {short m = Con Vert. ToInt16 (New Random ().                Next (2, 20));                RData = null;                byte[] bs = Receive (m, id, address, Len);                Byte[] B = Trimmodbus (BS, M, ID, Len);                if (B==null) {return false;}                list<short> data = new list<short> (255); for (int i = 0; i < b.length-1; i++) {if (! Convert.toboolean (I & 1)) {byte[] temp = new byte[] {b[i+1], b[i]}; Data.                   ADD (bitconverter.toint16 (temp, 0)); }} rData = data.                ToArray ();            return true;                } catch (Exception e) {loghelper.writelog ("Return Modbus data Error" + e.message);            return false; }        }
This is actually more to deal with the data anomalies, loghelper and the same as before, the core seems to be gone, that is the Receive method.
        <summary>///Read Modbus///00-xx 0d 0A 14 00 14 00 14 00 14 00 14 00 </summary>//<param name= "M" > Mark </param>//<param name= "id" > Device code </p        aram>//<param name= "Address" > Start address </param>//<param name= "Len" > Number of Devices </param>        <returns></returns> Private byte[] Receive (short m, short ID, short address, short Len)                {try {if (tcpClient = = NULL | |!tcpclient.connected) {return null;}                                byte[] data = Getsrcdata (m, id, address, Len); A. (data, data, tcpClient.Client.Send) at the xx-xx.                Length, Socketflags.none);                int size = Len * 2 + 9;                byte[] RData = new Byte[size];                TcpClient.Client.Receive (rData, size, socketflags.none); string T1 = Tranbytes(RData);            return rData; }catch (SocketException e) {if (E.errorcode! = 10004) {Loghelper.writelog                (E.message);                    } if (tcpClient! = null) {tcpclient.close ();                TcpClient = null;            } return null; }} #endregion
The above code can be said to be the core of Modbus protocol, is actually the socket to send data and accept data, send is to tell the host to take those data. Acceptance is the acceptance of the data returned by the host.
Send//00 at $////<summary>//////</summary> <param name= "M" ></param>//<param name= "len" ></param>//<param Nam        E= "id" ></param>//<param name= "Address" ></param>//<returns></returns> Private byte[] Getsrcdata (short m, short ID, short add, short len) {list<byte> data = new            List<byte> (255); Data.                     AddRange (ValueHelper.Instance.GetBytes (m)); Data.                            AddRange (new byte[] {0x00, 0x00}); XX data.    AddRange (ValueHelper.Instance.GetBytes (convert.toint16 (6))); The number of bytes is data.                                        ADD (Convert.tobyte (id)); The route code is data.                                         Add (Convert.tobyte (3)); function Code 03           Data.                   AddRange (ValueHelper.Instance.GetBytes (add)); Start address, data.                   AddRange (ValueHelper.Instance.GetBytes (len)); The number of devices is return data.        ToArray (); }
  Well, it's basically done here. In fact, a lot of logic in the code, said the simple is an ID device, from which address, read a few device values, here need to note is short do not use 32-bit int to replace, the result will be different. Take a closer look at the estimate that everyone can understand and there is nothing mysterious about it. Oh, yes, and Valuehelper code.
Using system;using system.collections.generic;using system.text;namespace Modbus {public class Valuehelper {        #region Size End Judge public static bool Littleendian = FALSE;                Static Valuehelper () {unsafe {int tester = 1;            Littleendian = (* (byte*) (&tester)) = = (byte) 1;        }} #endregion #region Factory public static valuehelper _instance = null;                Internal static Valuehelper Instance {get {if (_instance = = null)                    {_instance = Littleendian? New Littleendianvaluehelper (): New Valuehelper ();                _instance = new Valuehelper ();            } return _instance; }} #endregion protected Valuehelper () {} public virtual byte[] GetBytes (short     Value) {return bitconverter.getbytes (value);   } public virtual byte[] GetBytes (int value) {return bitconverter.getbytes (value);        } public virtual byte[] GetBytes (float value) {return bitconverter.getbytes (value);        } public virtual byte[] GetBytes (double value) {return bitconverter.getbytes (value);        } public virtual short getshort (byte[] data) {return bitconverter.toint16 (data, 0);        } public virtual int GetInt (byte[] data) {return Bitconverter.toint32 (data, 0);        } public virtual float getfloat (byte[] data) {return Bitconverter.tosingle (data, 0);        } public virtual Double getdouble (byte[] data) {return bitconverter.todouble (data, 0);        }} internal class Littleendianvaluehelper:valuehelper {public override byte[] GetBytes (short value) {return this. Reverse (bitconverter.getbytES (value)); } public override byte[] GetBytes (int value) {return this.        Reverse (bitconverter.getbytes (value)); } public override byte[] GetBytes (float value) {return this.        Reverse (bitconverter.getbytes (value)); } public override byte[] GetBytes (double value) {return this.        Reverse (bitconverter.getbytes (value)); } public virtual short getshort (byte[] data) {return bitconverter.toint16 (this.        Reverse (data), 0); } public virtual int GetInt (byte[] data) {return Bitconverter.toint32 (this.        Reverse (data), 0); } public virtual float getfloat (byte[] data) {return Bitconverter.tosingle (this.        Reverse (data), 0); } public virtual Double getdouble (byte[] "data" {return bitconverter.todouble (this).        Reverse (data), 0);         } private byte[] Reverse (byte[] data) {   Array.reverse (data);        return data; }    }}
The code is probably all posted, but if you really want to run, it needs to be easy to clean up.

C # read Modbus data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.