UWP读取和写入串行崩溃

时间:2019-04-26 08:55:31

标签: c# uwp

我正在使用c#uwp连接到串行端口以发送命令。当我打了几次电话。它会自动崩溃。 以下是异常消息。 Realink.Guard.exe中0x77CF806C(ntdll.dll)的未处理异常:0xC000000D:无效参数已传递给服务或函数。

公共静态类对讲机     {

    private static SerialDevice serialDevice;

    private static CancellationTokenSource WriteCancellationTokenSource;
    private static CancellationTokenSource ReadCancellationTokenSource;

    private static Object WriteCancelLock = new Object();
    private static Object ReadCancelLock = new Object();
    private static string LastReceivedMessage = "";
    private static StringBuilder sbAccMessage = new StringBuilder();

    public static async Task<bool> InitializeIntercomAsync(string portName)
    {
        try
        {
            var deviceSelector = SerialDevice.GetDeviceSelector(portName);
            var devices = await DeviceInformation.FindAllAsync(deviceSelector);
            if (devices.Any())
            {
                var deviceId = devices.First().Id;
                serialDevice = await SerialDevice.FromIdAsync(deviceId);

                if (serialDevice != null)
                {
                    serialDevice.BaudRate = 115200;
                    serialDevice.StopBits = SerialStopBitCount.One;
                    serialDevice.DataBits = 8;
                    serialDevice.Parity = SerialParity.None;
                    serialDevice.Handshake = SerialHandshake.None;

                    while (true)
                    {
                       string message = await ListenToSerialPort();
                        sbAccMessage.Append(message);
                        //var messageDialog = new MessageDialog(message);
                        //await messageDialog.ShowAsync();
                        if (message.ToLower().Contains("ring") && !LastReceivedMessage.ToLower().Contains("ring"))
                        {
                            await Realink.Guard.Common.UtilitiesService.PlayMusicAsync("Ringtone.mp3");
                            Common.ContentDialogMaker.IncomingCallContentDialog = new Control.IncomingCallContentDialog("incoming","Unknown Number", "Unknown", "Unknown");
                            await Common.ContentDialogMaker.CreateContentDialogAsync(Common.ContentDialogMaker.IncomingCallContentDialog, false);

                        }
                        LastReceivedMessage = message;
                    }
                }
            }
            return true;

        }
        catch (Exception ex)
        {
            return false;
        }
    }



    public static async Task Call(string contactNo)
    {
        Common.CommonVariable.Log("Start", "Intercom");
        LastReceivedMessage = "";

        //await WriteToSerialPort("AT+CREG?\r");
        //await WriteToSerialPort("AT+CGREG?\r");

        await WriteToSerialPort("ATD" + contactNo + ";\r");
        Common.CommonVariable.Log("End", "Intercom");
    }

    public static async Task AnswerCall()
    {
        Common.CommonVariable.Log("Start", "Intercom");

        LastReceivedMessage = "";
        Realink.Guard.Common.UtilitiesService.MediaPlayer_Pause();
        await WriteToSerialPort("ATA;\r");
        Common.CommonVariable.Log("End", "Intercom");
    }
    public static async Task HangUpCall()
    {

        Common.CommonVariable.Log("Start", "Intercom");

        LastReceivedMessage = "";
        Realink.Guard.Common.UtilitiesService.MediaPlayer_Pause();
        await WriteToSerialPort("ATH;\r");
        Common.CommonVariable.Log("End", "Intercom");
    }

    public static async Task<string> ListenToSerialPort()
    {
        Common.CommonVariable.Log("Start", "Intercom");

        try
        {
            if (serialDevice != null)
            {
                using (DataReader DataReaderObject = new DataReader(serialDevice.InputStream))
                {                       
                    ReadCancellationTokenSource = new CancellationTokenSource();


                    Task<UInt32> loadAsyncTask;

                    // Don't start any IO if we canceled the task
                    lock (ReadCancelLock)
                    {
                        // Cancellation Token will be used so we can stop the task operation explicitly
                        // The completion function should still be called so that we can properly handle a canceled task
                        ReadCancellationTokenSource.Token.ThrowIfCancellationRequested();

                        // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
                        DataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

                        // Create a task object to wait for data on the serialPort.InputStream
                        loadAsyncTask = DataReaderObject.LoadAsync(7).AsTask(ReadCancellationTokenSource.Token);
                    }


                    UInt32 bytesRead = await loadAsyncTask;
                    String output = String.Empty;
                    if (bytesRead > 0)
                    {
                        output = DataReaderObject.ReadString(bytesRead);
                    }
                    Common.CommonVariable.Log("End", "Intercom");
                    return output;
                }                 
            }
            return "";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        finally
        {
            Common.CommonVariable.Log("End", "Intercom");
        }
    }



    public static async Task WriteToSerialPort(string command)
    {
        Common.CommonVariable.Log("Start", "Intercom");

        if (serialDevice == null)
        {
            await InitializeIntercomAsync(Common.SessionService.GetSessionString(Key.LocalSettingKey.INTERCOME_PORT));
        }
        if (serialDevice != null)
        {
            using (DataWriter DataWriterObject = new DataWriter(serialDevice.OutputStream))
            {
                DataWriterObject.WriteString(command);
                WriteCancellationTokenSource = new CancellationTokenSource();

                Task<UInt32> storeAsyncTask;

                // Don't start any IO if we canceled the task
                lock (WriteCancelLock)
                {
                    WriteCancellationTokenSource.Token.ThrowIfCancellationRequested();

                    // Cancellation Token will be used so we can stop the task operation explicitly
                    // The completion function should still be called so that we can properly handle a canceled task
                    storeAsyncTask = DataWriterObject.StoreAsync().AsTask(WriteCancellationTokenSource.Token);
                }

                UInt32 bytesWritten = await storeAsyncTask;
            }

        }
        Common.CommonVariable.Log("End", "Intercom");
    }

0 个答案:

没有答案