SmallHan

  对于web服务来说,一般部署在服务器端的,所以读取串口数据是比较难的,虽然有对应的插件,但实际效果怎么样也不知道,没有尝试过!目前我是通过winform的形式读取串口数据(将winform作为一个服务),然后与Web建立通讯,实现数据的同步。

    1.什么是串口通讯?(PS:之前没接触过串口)  参考文章:https://www.toutiao.com/i6743040148734214663/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1590294310&app=news_article&utm_source=weixin&utm_medium=toutiao_android&req_id=2020052412250901012903209402503345&group_id=6743040148734214663

     2.建立websocket服务

  2.1 目前我引用该dll websocket-sharp来实现WebSocket服务端,可以直接从nuget上下载,以下是代码实例

 class Program
    {
        static void Main(string[] args)
        {
            var wssv = new WebSocketServer("ws://localhost:8080/");
            wssv.AddWebSocketService<Server>("/Server");
            wssv.Start();
            Console.ReadKey(true);
            wssv.Stop();
        }
    }

 public class Server : WebSocketBehavior
    {
        protected override void OnOpen()
        {
            Console.WriteLine("Server start..");
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            Sessions.Broadcast(e.Data);
        }
        protected override void OnClose(CloseEventArgs e)
        {
            base.OnClose(e);
        }
        protected override void OnError(ErrorEventArgs e)
        {
            base.OnError(e);
        }
    }

 

    3.读取串口数据的程序,并与websocket服务建立通讯

  3.1 如何打开串口呢?

    这里会用到微软提供的类SerialPort,需配置端口,波特率,数据位,停止位(这些概念可以从上面文章中了解到),这里我比较懒,直接从github下载个现成二次修改,链接:https://github.com/naihaishy/SerialPort-Communication

       3.2  与websocket建立通讯,其中InitWsSocket 需要窗体加载的时候调用该方法

private WebSocketSharp.WebSocket client;
const string host = "ws://localhost:8080/Server";

 private void InitWsSocket()
        {
            client = new WebSocketSharp.WebSocket(host);
            client.OnOpen += (s, e) => textBoxReceive.Text +=string.Format("WsConnect is open.\r\n");
            client.OnError += (s, e) => textBoxReceive.Text += string.Format("WsError:{0}\r\n", e.Message);
            client.OnMessage += (s, e) => textBoxReceive.Text += string.Format("WsServer:{0}\r\n", e.Data);
            client.OnClose += (s, e) => textBoxReceive.Text += string.Format("WsConnect is close.\r\n");
            client.Connect();
}

   3.3  当接收到串口数据的时候,往webSocket推数据(因目前采用的是广播机制,所以所有监听的客户端都能收到该消息)

 private void buttonSendData_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                MessageBox.Show("请先打开串口", "Error");
                return;
            }

            String strSend = textBoxSend.Text;//发送框数据
            if (radioButtonSendDataASCII.Checked == true)//以字符串 ASCII 发送
            {
                serialPort.WriteLine(strSend);//发送一行数据 
                //服务器推送数据
                client.Send(strSend);
            }
            else
            {
                //16进制数据格式 HXE 发送
                 
                char[] values = strSend.ToCharArray();
                foreach (char letter in values)
                {
                    // Get the integral value of the character.
                    int value = Convert.ToInt32(letter);
                    // Convert the decimal value to a hexadecimal value in string form.
                    string hexIutput = String.Format("{0:X}", value);
                    serialPort.WriteLine(hexIutput);

                }



            }

        }        

    4.web端与WebSocket服务建立通讯,以及事件的触发

var wsUri = "ws://localhost:8080/Server";

$(function () {
    wsInit();
  });
  function wsInit() {
    let websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) {
    };
    websocket.onclose = function(evt) {
    };
    websocket.onmessage = function(evt) {
      var received_msg = evt.data;
      console.log(received_msg);
      $("#WareLeviteVM_Entity_Weight").val(received_msg);
    };
    websocket.onerror = function(evt) {
    };

  }

 

    5.效果如下图所示

    6.目前代码是不完善的,还有许多细节要考虑,比如断开重连,等等!

分类:

技术点:

相关文章: