Example #1
0
        public async Task SendData(string msg)
        {
            var x = Encoding.UTF8.GetBytes(msg);
            var p = new CancellationTokenSource();

            // 第一次加载
            if (serialPort == null)
            {
                serialPort = await getSerialPort();
            }

            if (serialPort != null)
            {
                // 运行过程中串口断开了
                if (serialPort.serialPort == null)
                {
                    serialPort.ReceiveHandler -= SerialPort_ReceiveHandler;
                    serialPort = await getSerialPort();
                }

                if (serialPort != null)
                {
                    await serialPort.Send(x.Concat(new byte[] { 0x0D, 0x0A }).ToArray(), p.Token);
                }
            }
        }
        public async Task Send(BaseDirective item, int reSendTimes = 0)
        {
            try
            {
                waitForFeedbackDirectives.TryAdd(item.DirectiveId, new WaitForFeedBack(DateTime.Now, item, reSendTimes));

                var directiveData = protocolProvider.GenerateDirectiveBuffer(item);
                //第一次加载
                if (serialPort == null)
                {
                    serialPort = await getSerialPort();
                }

                if (serialPort != null)
                {
                    // 运行过程中串口断开了
                    if (serialPort.serialPort == null)
                    {
                        serialPort.ReceiveHandler -= SpHelper_ReceiveHandler;
                        serialPort = await getSerialPort();
                    }

                    if (waitForFeedbackDirectives.ContainsKey(item.DirectiveId) && serialPort != null)
                    {
                        await serialPort.Send(directiveData, cancelTokenSource.Token);
                    }
                }
            }
            catch (CustomException e)
            {
                Debug.WriteLine("send error->" + e.Message);
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("send cancel");
            }
            catch (Exception e)
            {
                OnErrorEvent(new CustomException(e.Message + "Send", this.GetType().FullName,
                                                 ExceptionPriority.Unrecoverable), item);
            }
        }