Exemplo n.º 1
0
 /// <summary>
 /// 关闭COM口
 /// </summary>
 /// <returns></returns>
 public void Close()
 {
     if (sp != null)
     {
         if (sp.IsOpen)
         {
             try
             {
                 sp.Close();
             }
             catch
             {
             }
         }
     }
     Status = AppStatus.停止;
 }
Exemplo n.º 2
0
        /// <summary>
        /// websocket服务,因为一开始就需要打开,在一开始打开
        /// </summary>

        #region 打开、关闭COM口
        /// <summary>
        /// 打开COM口
        /// </summary>
        /// <param name="portName">COM口名称</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="parity">奇偶校验位</param>
        /// <param name="stopBits">停止位</param>
        /// <returns></returns>
        public void Start()
        {
            Task.Run(async() => { await mqttclient.ConnectMqttServerAsync(); });
            if (!sp.IsOpen)
            {
                try
                {
                    sp.PortName     = Setting.PortName;
                    sp.BaudRate     = Setting.BaudRate;
                    sp.DataBits     = Setting.DataBits;
                    sp.Parity       = Setting.Parity;
                    sp.StopBits     = Setting.StopBits;
                    sp.DtrEnable    = true; //启用控制终端就续信号
                    sp.RtsEnable    = true; //启用请求发送信号
                    sp.ReadTimeout  = 1000;
                    sp.WriteTimeout = 1000;
                    sp.Open();
                    Status = AppStatus.监听;
                    //发送数据请求
                    byte[] crcBytes     = new byte[2];
                    byte[] sendResponse = new byte[6 + crcBytes.Length];
                    sendResponse[0] = 0x01;
                    sendResponse[1] = 0x03;
                    sendResponse[2] = 0x00;
                    sendResponse[3] = 0x00;
                    sendResponse[4] = 0x00;
                    sendResponse[5] = 0x07;
                    GetCRC(sendResponse, ref crcBytes);
                    sendResponse[sendResponse.Length - 1] = crcBytes[1]; //高8位
                    sendResponse[sendResponse.Length - 2] = crcBytes[0]; //低8位

                    sp.Write(sendResponse, 0, sendResponse.Length);
                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
                }
                catch (Exception e)
                {
                    Status = AppStatus.停止;
                    Console.Write(e.ToString());
                }
            }
        }