C# 实现读取电子秤数据-通过websocket发送数据给本地网页

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Net;

// websocket
using Fleck;

// 读取json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// 串口
using System.IO.Ports;

namespace ConsoleApplication1
{
    class Program
    {
        private static SerialPort port;
        private static IWebSocketConnection socketer;
        private static string balancePort = "COM1";
        private static int balancePortBaudRate = 9600;
        private static string webServerPort = "80";
        private static string websocketPort = "8081";
        private static int delayTime = 500;

        // 工具 - http请求
        public static string CommonHttpRequest(string data, string uri, string type)
        {
            //Web访问对象,构造请求的url地址
            string serviceUrl = uri;

            //构造http请求的对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //转成网络流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            //设置
            myRequest.Method = type;
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            // 发送请求
            // Stream newStream = myRequest.GetRequestStream();
            // newStream.Write(buf, 0, buf.Length);
            // newStream.Close();
            // 获得接口返回值
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }

        // websocket服务
        public static void websocketServer()
       {
           Console.WriteLine("websocket服务启动");
           var server = new WebSocketServer("ws://0.0.0.0:" + websocketPort);
           server.Start(socket =>
           {
               socketer = socket;
               Console.WriteLine("socket.GetType()");
               Console.WriteLine(socket.GetType());
               Console.WriteLine("socket.GetType()");
               socket.OnOpen = () =>
               {
                   Console.WriteLine("Open!");
                   socket.Send("{\"MsgType\":\"init\"}");
               };
               socket.OnClose = () => Console.WriteLine("Close!");
               socket.OnMessage = (message) =>
               {
                   Console.WriteLine(message);
               };

           });
       }

        // web服务
        public static void webServer()
        {
            HttpListener httpListener = new HttpListener();
            httpListener.Prefixes.Add(string.Format("http://+:{0}/", webServerPort));
            httpListener.Start();
            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始异步接收request请求
            Console.WriteLine("web服务启动");
        }
        static void GetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context(一个环境封装体)
            context.Response.StatusCode = 200;

            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            String url = request.RawUrl;
            Console.WriteLine(request.RawUrl);
            if (url == "/")
            {
                url = "/index.html";
            }
            if (url.EndsWith("html") || url.EndsWith("js") || url.EndsWith("json"))
            {
                response.ContentType = "html";
                response.ContentEncoding = Encoding.UTF8;

                using (Stream output = response.OutputStream)
                {
                    Console.WriteLine("." + url);
                    string text = System.IO.File.ReadAllText("." + url);
                    byte[] buffer = Encoding.UTF8.GetBytes(text);
                    output.Write(buffer, 0, buffer.Length);
                }
            }
        }
        
        // 电子秤
        public static void balanceServer()
        {
            // 电子秤
            port = new SerialPort();
            port.PortName = balancePort;//通信端口
            port.BaudRate = balancePortBaudRate;//波特率
            port.Parity = Parity.None;//校验法:无
            port.DataBits = 8;//数据位:8
            port.StopBits = StopBits.One;//停止位:1

            port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); //设置数据接收事件(监听)

            //开启电子秤端口
            StartSerialPortMonitor();
        }

        /// 接收 COM 数据接收事件(监听)
        /// <summary>
        /// 接收 COM 数据接收事件(监听)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(delayTime);//线程休眠500毫秒,方便接收串口的全部数据
            try
            {
                if (!port.IsOpen)
                {
                    Console.WriteLine("串口不能读取数据");
                    return;
                }
                byte[] readBuffer = new byte[port.ReadBufferSize];
                try
                {
                    int count = port.Read(readBuffer, 0, port.ReadBufferSize);        //读取串口数据(监听)
                    String weight = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);//将字节数组解码为字符串
                    if (count != 0)
                    {
                        // weight = System.Text.RegularExpressions.Regex.Replace(weight, @"[^0-9]+", "");
                        Console.WriteLine(weight);
                        if (socketer == null) {
                            Console.WriteLine("socketer: 没有连接...可能尚未连接websocket...或者关闭串口重新连接");
                            return;
                        }
                        // todo 这里最后我们会采用 websocket 发送消息
                        socketer.Send("{\"MsgType\":\"balance\",\"weight\":\"" + weight + "\"}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发送数据失败: ", ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        /// 开启串口监听
        /// <summary>
        /// 开启串口监听
        /// </summary>
        /// <param name="args"></param>
        private static void StartSerialPortMonitor()
        {
            try
            {
                port.Open();//打开串口
                Console.WriteLine("电子秤启动");
                // port.DtrEnable = true;//设置DTR为高电平
                // port.RtsEnable = true;//设置RTS位高电平
            }
            catch (Exception ex)
            {
                //打开串口出错,显示错误信息
                Console.WriteLine("打开电子秤串口失败");
                Console.WriteLine(ex.Message);
                return;
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("开始启动程序...");
            // 读取配置文件
            string configStr = System.IO.File.ReadAllText("config.json");
            JObject config = (JObject)JsonConvert.DeserializeObject(configStr);
            try
            {
                webServerPort = config["webServer"]["port"].ToString();// 设定webServer端口
                websocketPort = config["websocket"]["port"].ToString();// 设定websocket端口
                balancePort = config["balance"]["port"].ToString();// 设定电子秤端口
                balancePortBaudRate = (int)config["balance"]["baudRate"];// 设定电子秤接收波特率
                delayTime = (int)config["balance"]["delayTime"];// 设定电子秤接收延迟时间(毫秒)
            }
            catch
            {
                Console.WriteLine("配置文件不全");
            }

            // websocket服务
            Thread threadWebsocket = new Thread(new ThreadStart(websocketServer));
            threadWebsocket.Start();

            // WEB服务器
            Thread threadWebServer = new Thread(new ThreadStart(webServer));
            threadWebServer.Start();

            // 电子秤
            Thread threadBalance = new Thread(new ThreadStart(balanceServer));
            threadBalance.Start();

            Console.ReadKey();
        }
    }
}

config.json

{
	"webServer": {
		"port": 8080
	},
	"websocket": {
		"port": 18081
	},
	"balance": {
		"port": "COM1",
		"baudRate": 9600,
		"delayTime": 500
	}
}

所需dll

Fleck.dll
Newtonsoft.Json.dll

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值