一文了解基于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 AI 眼鏡讓百萬 APP「集體失業(yè)」?
- 2 大廠紛紛入局,百度、阿里、字節(jié)搶奪Agent話語權(quán)
- 3 深度報告|中國AI產(chǎn)業(yè)正在崛起成全球力量,市場潛力和關(guān)鍵挑戰(zhàn)有哪些?
- 4 一文看懂視覺語言動作模型(VLA)及其應(yīng)用
- 5 上海跑出80億超級獨角獸:獲上市公司戰(zhàn)投,干人形機器人
- 6 國家數(shù)據(jù)局局長劉烈宏調(diào)研格創(chuàng)東智
- 7 下一代入口之戰(zhàn):大廠為何紛紛押注智能體?
- 8 百億AI芯片訂單,瘋狂傾銷中東?
- 9 Robotaxi新消息密集釋放,量產(chǎn)元年誰在領(lǐng)跑?
- 10 格斗大賽出圈!人形機器人致命短板曝光:頭腦過于簡單