C # Read and write Omron (Omron) PLC, C # Read and write data using the FINS-TCP protocol

Source: Internet
Author: User

This article will use a GitHub open source component technology to read and write Siemens PLC data, using the Ethernet-based TCP/IP implementation, no additional components, read operations as long as the background thread will not be stuck thread, this component supports super convenient high-performance read and write operation

GitHub Address: Https://github.com/dathlin/HslCommunication If you like star or fork, you can also enjoy support.

中文版 version:https://github.com/dathlin/hslcommunication/blob/master/docs/siemens.md

You can download the installation in NuGet Manager in Visual Studio, or you can enter the following instructions directly in the NuGet console

Install-package hslcommunication

If you need a tutorial: NuGet installation Tutorial: http://www.cnblogs.com/dathlin/p/7705014.html

Technical Support QQ Group: 592132877 (the component version update details will be released in the group first) Last modified: April 5, 2018 19:00:08

Inside all kinds of small partners, for you to answer data interaction, programming skills, if you have any questions about the API provided by this interface, you can add group consultation, if there are better suggestions, welcome to put forward.

Complete information about the components and other API descriptions refer to: The Http://www.cnblogs.com/dathlin/p/7703805.html component's authorization protocol, the update log, all within the page.

This article will show you how to configure the network parameters and how to use the code to access the PLC data, hoping to give the people in need to solve some practical problems. Mainly for Siemens PLC M,Q,I,DB block data read and write, pro-test effective.

Here the use of the direct way of the network cable, if the PLC is connected to the LAN, you can read and write remotely ^_^

There are 2 namespaces used here:

Using hslcommunication;using HslCommunication.Profinet.Omron;

Just talk.

When a host computer needs to read 100 Siemens PLC equipment (here is just for example, usually use Modbus TCP is the same), you use the server initiative to request the mechanism of 100 devices is a great test of performance, If you open 100 threads to poll 100 devices, then the performance loss will be very large, not to mention the addition of equipment, if the installation of Modbus TCP server, can be a perfect solution to the performance problem, because the connection pressure will be evenly distributed to each plc, Server side as long as a new timestamp to know that the client has no connection.

We add the Modbus TCP method to 100 plc, send the data to the server's IP and port, the server distinguishes the device according to station number. This makes it possible to build a high-performance terminus. This component supports the fast setting up of a high performance Modbus TCP terminus.

Http://www.cnblogs.com/dathlin/p/7782315.html

about two modes

All of the client classes provided by this component, including Mitsubishi, Siemens, Omron, Modbus-tcp, and Simplifynet, are inherited from the dual-mode base class, and the dual-mode includes a short connection and a long connection, and the following details the differences between the next two modes

Short Connection : Each read and write is a separate request, the request is closed, if the server's port only supports single connection, then the port can be reused after shutdown, but in frequent network requests, prone to abnormal, there will be other requests unsuccessful, Especially in the case of multithreading.

Long Connection : Create a common connection channel, all the read and write requests to use this channel to complete, so that the read and write performance faster, instant multi-threaded calls will not affect the internal synchronization mechanism. If the server's port only supports a single connection, then this port is occupied, such as the port mechanism of Mitsubishi, Siemens Modbus TCP port mechanism is also the case. The following code uses long connections by default, with higher performance and multi-threaded synchronization.

In the short-connected mode, each request is a separate access, so there is no reconnection, in the long-connected mode, if this request fails, the next time the request, it will automatically reconnect to the server until the request is successful. In addition, as far as possible, all reading and writing are judged on the success of the results.

About Logging

Whether it is Mitsubishi's data access class, or Siemens, or Modbus TCP Access class, there is a lognet property used to record the log, the property is an interface class, Ilognet, everything inherits the interface can be used to record the log, the log will be in the failure of access, This is especially true because the network causes logging when Access fails (if you have a real logger configured for this lognet property): If you want to use this logging feature, please follow the blog below to instantiate it:

Http://www.cnblogs.com/dathlin/p/7691693.html

As an example:

Omronfinsnet.lognet = new HslCommunication.LogNet.LogNetSingle ("Omron.log.txt");

a description of the communication

Using the FINS-TCP protocol for data interaction, if a write failure is found during the test, it may be because

Accessing test projects

In the above GitHub source code, there is a test project, Hslcommunicationdemo, which contains a variety of client-side demo project, do not need to write any code to test the data access.

For:

Demo Project

The following three shows how to access the data of the PLC, we usually need to process after the access, the following example project shows the background from the PLC reading data, the foreground display and push to all the online client functions, clients and graphical display, with a certain reference, the project address is:

Https://github.com/dathlin/RemoteMonitor

The following picture example of the left side of the program is the server program, it should be directly connected with the PLC and access to the local area network, and then push the data to the client display. Note: A sophisticated program should separate the processing logic programs and interface programs, such as the server program here to achieve data collection, push, storage. Let the client program to implement data collation, analysis, display, so that even if the client program because of a bug, the server can still work properly.

Demo Project using Siemens access, can be easily converted to Omron project

Address support

Support addresses and examples are as follows:

    • DM District D100
    • CIO Area C100
    • WR Zone W100
    • HR Area H100
    • AR Zone A100

Special thanks
    • Thanks for the wine strike . Testing of this component
    • Thank you for a water test of this component

Instantiation of
Private Omronfinsnet omronfinsnet = new Omronfinsnet ("192.168.0.100", 6000);

Before connecting to the server need to set three parameters, PLC unit number, PLC network node, PC network node, as follows is an example, you need to fill in according to the actual situation.

            OMRONFINSNET.SA1 = 0x20; PC network number, the last number of IP addresses of the PC            omronfinsnet.da1 = 0x10;//PLC network number, the last number of IP addresses of the plc            OMRONFINSNET.DA2 = 0x00;//plc Unit number, is typically 0

connection server, can also be placed in the window's Load method, it is generally recommended to use a long connection, faster, but also thread-safe (call the following method is to use a long connection, if you do not directly read data, it is a short connection):
            Try            {                Operateresult connect = Omronfinsnet.connectserver ();                 if (connect. issuccess)                {                    MessageBox.Show ("Connection succeeded! " );                }                else                {                    MessageBox.Show ("Connection failed! " );                }            }            catch (Exception ex)            {                MessageBox.Show (ex. Message);            }

Disconnect, that is, close the long connection, if the request data, it becomes a short connection

Omronfinsnet.connectclose ();

The following is a demonstration of some simple data operations, eliminating the success of the validation of the results, all read and write results are operateresult type and derived type, there is a issuccess attribute to determine the success or not

            Read operation, where the D100 can replace the c100,a100,w100,h100 effect when the same bool d100_7 = Omronfinsnet.readbool ("D100.7").  Content; Read if the D100.7 is off, note that D100.0 is equivalent to D100 short short_d100 = omronfinsnet.readint16 ("D100"). Content; Read the D100 composed of the word ushort ushort_d100 = omronfinsnet.readuint16 ("D100"). Content; Reads a D100 composed of unsigned values int int_d100 = Omronfinsnet.readint32 ("D100").         Content; Read d100-d101 composed of signed data uint UINT_D100 = Omronfinsnet.readuint32 ("D100").      Content; Read d100-d101 composed of unsigned values float float_d100 = omronfinsnet.readfloat ("D100").   Content; Read d100-d101 composed of single-precision values long long_d100 = Omronfinsnet.readint64 ("D100").      Content; Read d100-d103 a large data value of ulong ulong_d100 = Omronfinsnet.readuint64 ("D100").   Content; Read d100-d103 composed of unsigned big data double double_d100 = omronfinsnet.readdouble ("D100"). Content; Read d100-d103 composed of double values string str_d100 = Omronfinsnet.readstring ("D100", 5). Content;Read d100-d104 composed of ASCII string data//write operation, here D100 can replace the c100,a100,w100,h100 effect when the same omronfinsnet.write ("D100"            , (byte) 0x33);          Write single byte Omronfinsnet.write ("D100", (short) 12345);         Write double-byte signed Omronfinsnet.write ("D100", (ushort) 45678);      Write double-byte unsigned omronfinsnet.write ("D100", (UINT) 3456789123);              Write double-word unsigned omronfinsnet.write ("D100", 123.456f);     Write single precision Omronfinsnet.write ("D100", 1234556434534545L);     Write large integers with signed omronfinsnet.write ("D100", 523434234234343UL);              Write large integer unsigned omronfinsnet.write ("D100", 123.456d); Write double precision Omronfinsnet.write ("D100", "K123456789");//write ASCII string

The following is a description of complex data operations, as well as bulk data operations, such as reading d100-d105

            operateresult<byte[]> read = Omronfinsnet.read ("D100", 5);            {                if (read. issuccess)                {                    //Here you need to customize to handle complex data based on the actual situation short                    D100 = omronFinsNet.ByteTransform.TransInt16 (read. Content, 0);                    Short D101 = omronFinsNet.ByteTransform.TransInt16 (read. Content, 2);                    Short D102 = omronFinsNet.ByteTransform.TransInt16 (read. Content, 4);                    Short D103 = omronFinsNet.ByteTransform.TransInt16 (read. Content, 6);                    Short D104 = omronFinsNet.ByteTransform.TransInt16 (read. Content, 7);                }                else                {                    //An exception occurred                }            }

Writes are the same, and can be manipulated in the opposite way.

If you want to implement a custom data type, you need to inherit an interface

public class usertype:hslcommunication.idatatransfer{#region Idatatransfer private HslCommunication.Core.IByteTra    Nsform bytetransform = new HslCommunication.Core.ReverseBytesTransform ();    Public ushort Readcount = 20;        public void ParseSource (byte[] Content) {int count = bytetransform.transint32 (content, 0);        float temp = Bytetransform.transsingle (Content, 4);        Short name1 = Bytetransform.transint16 (Content, 8);    String barcode = Encoding.ASCII.GetString (Content, 10, 10);        } public byte[] Tosource () {byte[] buffer = new BYTE[20]; Bytetransform.transbyte (count).        CopyTo (buffer, 0); Bytetransform.transbyte (temp).        CopyTo (buffer, 4); Bytetransform.transbyte (name1).        CopyTo (buffer, 8); Encoding.ASCII.GetBytes (barcode).        CopyTo (buffer, 10);    return buffer;    #endregion #region Public Data public int count {get; set;}    Public float Temp {get; set;} Public sHort name1 {get; set;}    public string Barcode {get; set;} #endregion}

So that we can read and write special data.

operateresult<usertype> read = omronfinsnet.readcustomer<usertype> ("M100"), if (read. issuccess) {    usertype value = read. Content;} Write Valueomronfinsnet.writecustomer ("M100", New Usertype ());

The reading of the ultimate data:

Here provides a core message reading mechanism, you can pass your own message, and then receive the server's message, and then their own resolution operation, can be implemented according to the message format arbitrary operation, of course, the premise is the need for message support. Suppose I want to implement read D0,D1, then the final message is

46494e530000001a000000020000000080000200210000c000000101820000000002

        private void Userbutton23_click_1 (object sender, EventArgs e)        {            byte[] buffer = HslCommunication.BasicFramework.SoftBasic.HexStringToBytes (                "  46494e530000001a000000020000000080000200210000c000000101820000000002");            Operateresult<byte[]> operate = omronfinsnet.readfromservercore (buffer);            if (operate. issuccess)            {                //display the message returned by the server                textboxappendstringline ( HslCommunication.BasicFramework.SoftBasic.ByteToHexString (operate. Content));            }            else            {                //Display network error                MessageBox.Show (operate. Tomessageshowstring ());            }        }

For more detailed information, you can refer to the test items in the source code.

Not easy to create, thanks for playing rewards

C # Read-write Omron (Omron) PLC, C # Read and write data using the FINS-TCP protocol

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.