Winform form uses WebApi interface to realize ModbusTCP data service

During the development process of the upper computer, sometimes it is necessary to provide data interfaces to MES or other systems. Today I will share with you how to develop WebApi interfaces in desktop applications such as Winform to provide data services for external modbus devices. The communication model is:

In order to better demonstrate the application scenario, this case takes reading the ModbusTCP device as an example. After the WeiApi interface is developed, the third-party system can read the device data through this interface.

The technical environment used in this example: VS2019, Modbus Slave, WebApi

1. Create a Winform program

2. Layout ui interface, the layout here is not fine and beautiful, but just a regular layout

3. Implement ModbusTCP connection

3.1 Install the Modbus Slave software, which is a simulation software for Modbus slave devices, used to simulate a Modbus Slave device, that is, the device of the lower computer, such as a temperature sensor, open the software,

3.2 Fill in three data

Set read save register data,

3.3. Nuget searches for modbustcp and installs it, so that ModbusTCP connection can be realized later.

3.4, the code of the “Establish Connection” button is as follows:

Pay attention to add the attribute object in the program.cs file, and assign the slave object to the global variable ModbusDevice when the connection is successful

Run the program, click the connection, it will show success

3.5 Disconnect code

4. Create HttpServer

4.1 First search these two libraries through Nuget, add a reference:

  • Microsoft.AspNet.WebApi.Client

  • Microsoft.AspNet.WebApi.SelfHost

  • 4.2 Create a class. HttpServer is mainly the encapsulation of HttpSelfHostServer. The HttpServer class is as follows: Full code:

  • using System;
    using System.Collections.Generic;
    using System. Linq;
    using System. Text;
    using System. Threading. Tasks;
    using System. Web. Http;
    using System.Web.Http.SelfHost;
    
    namespace WinFormsApI
    {
        public class HttpServer
        {
            private HttpSelfHostServer server;
            public HttpServer(string ip, int port)
            {
                var config = new HttpSelfHostConfiguration($"http://{ip}:{port}");//Create host service
                config.MapHttpAttributeRoutes();//Add routing attributes
                config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");//Specify routing rules
                server = new HttpSelfHostServer(config);
            }
            /// <summary>
            /// Start the service (asynchronous task mode)
            /// </summary>
            /// <returns></returns>
            public Task StartHttpServer()
            {
                return server. OpenAsync();
            }
            /// <summary>
            /// Close the service (asynchronous task mode)
            /// </summary>
            /// <returns></returns>
            public Task CloseHttpServer()
            {
                return server. CloseAsync();
            }
        }
    }
    

  • 4.3, add a class HomeController,

  • Write a method to read data in a holding register storage area, the code is as follows:

  • using EasyModbus;
    using System;
    using System.Collections.Generic;
    using System. Linq;
    using System. Text;
    using System. Threading. Tasks;
    using System. Web. Http;
    
    namespace WinFormsApI
    {
        public class HomeController : ApiController
        {
            public static ModbusClient mc;
    
            public HomeController()
            {
                mc = Program.ModbusDevice; //Get the specified attribute from the global variable
            }
            /// <summary>
            /// Read holding register
            /// </summary>
            /// <param name="address">Register address</param>
            /// <returns></returns>
            [HttpGet]
            public IHttpActionResult ReadKeepReg(int address)
            {
                int[] res = mc.ReadHoldingRegisters(address, 3);//Read the holding register data, starting from the specified address address, read 3 addresses
                string mes = "Temperature: " + res[0] + ", humidity: " + res[1] + ", light: " + res[2];
                return Json(mes);
            }
    
        }
    }
    

    5. The code to open the service button

  • close service button code

  • 6. Run the program

Open the browser and enter the access address: http://127.0.0.1:6688/api/home/ReadKeepReg?address=0

In this address format, http://127.0.0.1:6688 is the address and port set in the text box in the form form, api/home/ReadKeepReg is the method ReadKeepReg in the access controller homecontroller, address=0 is the parameter address in the method, 0 is the value of the parameter. The parameter value is 0 because the address number of the modbus slave device starts from 0. Finally, review the communication process: