一文了解基于WebApi實現(xiàn)ModbusTCP數(shù)據(jù)服務(wù)
前言
在上位機開發(fā)過程中,有時候會遇到需要提供數(shù)據(jù)接口給MES或者其他系統(tǒng),今天跟大家分享一下,如何在Winform等桌面應(yīng)用程序中,開發(fā)WebApi接口,提供對外數(shù)據(jù)服務(wù)。
為了更好地演示應(yīng)用場景,本案例以讀取ModbusTCP設(shè)備為例,開發(fā)好WeiApi接口后,第三方系統(tǒng)可以通過該接口讀取到設(shè)備數(shù)據(jù)。
實現(xiàn)過程
1、創(chuàng)建一個Winform程序,設(shè)計UI界面如下,主要包括ModbusTCP的設(shè)備IP及端口,以及本地WepApi的Http服務(wù)及端口:
2、實現(xiàn)ModbusTCP連接
(1)Nuget搜索xktComm并安裝,便于后續(xù)可以實現(xiàn)ModbusTCP連接
(2)建立ModbusTCP連接
private void btn_Connect_Click(object sender, EventArgs e)
{
if (CommonMethods.modbusTcp.Connect(this.txt_DevIp.Text, this.txt_DevPort.Text))
{
MessageBox.Show("設(shè)備連接成功");
}
else
{
MessageBox.Show("設(shè)備連接失敗");
}
}
(3)斷開ModbusTCP連接
private void btn_DisConn_Click(object sender, EventArgs e)
{
CommonMethods.modbusTcp.DisConnect();
}
3、創(chuàng)建HttpServer
首先通過Nuget搜索這兩個庫,添加一下引用:
Microsoft.AspNet.WebApi.ClientMicrosoft.AspNet.WebApi.SelfHost
HttpServer主要是對HttpSelfHostServer的封裝,HttpServer類如下:
public class HttpServer
{
private HttpSelfHostServer server;
public HttpServer(string ip, int port)
{
var config = new HttpSelfHostConfiguration($"http://{ip}:{port}");
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");
server = new HttpSelfHostServer(config);
}
public Task StartHttpServer()
{
return server.OpenAsync();
}
public Task CloseHttpServer()
{
return server.CloseAsync();
}
}
4、創(chuàng)建Controller創(chuàng)建一個控制器HomeController,以讀取保持寄存器為例,編寫了一個方法可以讀取一個保持寄存器存儲區(qū)數(shù)據(jù),代碼如下所示:
public class HomeController : ApiController
{
[HttpGet]
public IHttpActionResult ReadKeepReg(int address)
{
byte[] res = CommonMethods.modbusTcp.ReadKeepReg(address, 1);
return Json(res[0]*256+res[1]);
}
}
5、開啟HttpServer
(1)創(chuàng)建HttpServer對象
private HttpServer httpServer = null;
(2)開啟HttpServer服務(wù)
private async void btn_Start_Click(object sender, EventArgs e)
{
try
{
httpServer = new HttpServer(this.txt_Ip.Text, int.Parse(this.txt_Port.Text));
await httpServer.StartHttpServer();
MessageBox.Show("開始服務(wù)成功");
}
catch (Exception ex)
{
MessageBox.Show("開始服務(wù)失敗:"+ex.Message);
}
}
(3)停止HttpServer服務(wù)
private async void btn_Stop_Click(object sender, EventArgs e)
{
try
{
httpServer = new HttpServer(this.txt_Ip.Text, int.Parse(this.txt_Port.Text));
await httpServer.CloseHttpServer();
}
catch (Exception ex)
{
MessageBox.Show("停止服務(wù)失敗:" + ex.Message);
}
}
功能測試
首先用Modbus Slave開一個仿真:
運行上位機軟件后,連接設(shè)備并開啟服務(wù):
打開瀏覽器,輸入 http://127.0.0.1:2000/api/home/ReadKeepReg?address=0,即可獲取到40001的數(shù)據(jù)。

請輸入評論內(nèi)容...
請輸入評論/評論長度6~500個字
最新活動更多
推薦專題
- 1 小米YU7新增835公里續(xù)航版,6-7月面市
- 2 昆侖萬維24年營收56億,AI出海商業(yè)化獲重要進展
- 3 “AI寒武紀”爆發(fā)至今,五類新物種登上歷史舞臺
- 4 降薪、加班、裁員三重暴擊,“AI四小龍”已折戟兩家
- 5 大模型下半場:Agent時代為何更需要開源模型
- 6 中國“智造”背后的「關(guān)鍵力量」
- 7 全球無人駕駛技術(shù)排名:誰才是細分賽道的扛把子?
- 8 營收猛增46%,昆侖萬維成為AI“爆品工廠”
- 9 “6億年薪”系誤讀,理想官方:老板實際只拿266萬
- 10 從HR+AI到AI+HR,數(shù)智化本質(zhì)是“重構(gòu)”而非“替代”