简体   繁体   English

UWP C# 存储和加载串行设备信息

[英]UWP C# Store and Load Serial Device Information

I would like to find out how to store & load serial deviceinformation .我想了解如何存储和加载serial deviceinformation I have referred to UWP Serial Sample and tested the serial to RS485.我已经参考了UWP Serial Sample并测试了 RS485 的串口。

I am using a FTDI USB to UART-RS485 converter on raspberry pi running Windows IoT Core.我在运行 Windows IoT Core 的树莓派上使用 FTDI USB 到 UART-RS485 转换器。 I do not intend to use the onboard UART.我不打算使用板载 UART。 So I am wondering if I am able to save the SerialPort.id to Windows.Storage.ApplicationDataContainer and load it when the application starts to ensure it connects to the correct SerialPort .所以我想知道我是否能够将SerialPort.id保存到Windows.Storage.ApplicationDataContainer并在应用程序启动时加载它以确保它连接到正确的SerialPort

  1. How do I get the SerialPort readable name like USB-RS485-Cable etc .如何获得SerialPort可读名称,USB-RS485-Cable等。 becasue when i use SerialComsDisplay.Text = listOfDevices[SerialDeviceList.SelectedIndex].Id.ToString();因为当我使用SerialComsDisplay.Text = listOfDevices[SerialDeviceList.SelectedIndex].Id.ToString(); it read the ID which are in code.它读取代码中的ID

  2. It doesn't seems to load the correct SerialPort after i load it.我加载后似乎没有加载正确的SerialPort

Please help.请帮忙。 Thanks.谢谢。

Saving the SerialPort to containerSerialPort保存到container

    private void SaveSerialConfig_Click(object sender, RoutedEventArgs e)
    {
        Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

        localSettings.Values["SerialDevice"] = listOfDevices[SerialDeviceList.SelectedIndex].Name;
        SerialComsDisplay.Text = listOfDevices[SerialDeviceList.SelectedIndex].Id.ToString();
    }

Startup code to initialize the SerialPort when app starts应用程序启动时初始化SerialPort启动代码

private async void ListAvailablePorts()
    {
        try
        {
            string aqs = SerialDevice.GetDeviceSelector();
            var dis = await DeviceInformation.FindAllAsync(aqs);

            SerialComsDisplay.Text = "Select a device and connect";

            for (int i = 0; i < dis.Count; i++)
            {
                listOfDevices.Add(dis[i]);
            }

            DeviceListSource.Source = listOfDevices;
            SerialDeviceList.SelectedIndex = 0;
        }
        catch (Exception ex)
        {
            SerialComsDisplay.Text = ex.Message;
        }

        connectCommPort();
    }


private async void connectCommPort()
    {
        var selection = SerialDeviceList.SelectedItems;
        DeviceInformation entry;

        if (selection.Count <= 0)
        {
            SerialComsDisplay.Text = "\n Select a device and connect";
            return;
        }

        Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
        Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        if (localSettings.Values["SerialDevice"] != null)
        {
            var device = localSettings.Values["SerialDevice"];
            SerialComsDisplay.Text = device.ToString();
            entry = (DeviceInformation)device;
        }
        else
        {
            entry = (DeviceInformation)selection[0];
        }

        try
        {
            serialPort = await SerialDevice.FromIdAsync(entry.Id);
            if (serialPort == null) return;

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(0);//10 //1000
            serialPort.ReadTimeout = TimeSpan.FromMilliseconds(50);//100 //1000
            //serialPort.BaudRate = 9600;
            serialPort.BaudRate = 4800;
            serialPort.Parity = SerialParity.None;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;

            // Display configured settings
            SerialComsDisplay.Text = "Serial port configured successfully: ";
            SerialComsDisplay.Text += serialPort.BaudRate + "-";
            SerialComsDisplay.Text += serialPort.DataBits + "-";
            SerialComsDisplay.Text += serialPort.Parity.ToString() + "-";
            SerialComsDisplay.Text += serialPort.StopBits;

            // Set the RcvdText field to invoke the TextChanged callback
            // The callback launches an async Read task to wait for data
            SerialComsDisplay.Text = "Waiting for data...";

            // Create cancellation token object to close I/O operations when closing the device
            ReadCancellationTokenSource = new CancellationTokenSource();

            if (serialPort != null)
            {
                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataReaderObject = new DataReader(serialPort.InputStream);
            }

            Listen();

            startPollTimer();
        }
        catch (Exception ex)
        {
            SerialComsDisplay.Text = ex.Message;
        }
    }

1.How do I get the SerialPort readable name like USB-RS485-Cable etc . 1.如何获得 SerialPort 可读名称,如 USB-RS485-Cable 等。 becasue when i use SerialComsDisplay.Text = listOfDevices[SerialDeviceList.SelectedIndex].Id.ToString();因为当我使用 SerialComsDisplay.Text = listOfDevices[SerialDeviceList.SelectedIndex].Id.ToString(); it read the ID which are in code.它读取代码中的ID。

The property DeviceInformation.Name shows the readable name of the device.Please note that this property should only be used for display purposes only and not for finding a device because the Name can change due to localization or a user assigning a name.属性DeviceInformation.Name显示设备的可读名称。请注意,此属性仅应用于显示目的,而不应用于查找设备,因为名称可能会因本地化或用户分配名称而发生变化。

2.It doesn't seems to load the correct SerialPort after i load it. 2.加载后似乎没有加载正确的SerialPort。

I reviewed your code, found out that you stored the name of DeviceInformation as SerialDevice but not a object of DeviceInformation,我查看了您的代码,发现您将 DeviceInformation 的名称存储为 SerialDevice 而不是 DeviceInformation 的对象,

localSettings.Values["SerialDevice"] = listOfDevices[SerialDeviceList.SelectedIndex].Name;

however when you loaded the setting, you parse the string to object.但是,当您加载设置时,您会将字符串解析为对象。

var device = localSettings.Values["SerialDevice"];
SerialComsDisplay.Text = device.ToString();
entry = (DeviceInformation)device;

UPDATE:更新:

private async void connectCommPort()
{
    var selection = SerialDeviceList.SelectedItems;
    string deviceId;

    if (selection.Count <= 0)
    {
        SerialComsDisplay.Text = "\n Select a device and connect";
        return;
    }

    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    if (localSettings.Values["SerialDevice"] != null)
    {
        var deviceId = localSettings.Values["SerialDevice"];
        SerialComsDisplay.Text = deviceId;
    }
    else
    {
        deviceId = ((DeviceInformation)selection[0]).Id;
    }

    try
    {
        serialPort = await SerialDevice.FromIdAsync(deviceId );
        if (serialPort == null) return;

        // Configure serial settings
        serialPort.WriteTimeout = TimeSpan.FromMilliseconds(0);//10 //1000
        serialPort.ReadTimeout = TimeSpan.FromMilliseconds(50);//100 //1000
        //serialPort.BaudRate = 9600;
        serialPort.BaudRate = 4800;
        serialPort.Parity = SerialParity.None;
        serialPort.StopBits = SerialStopBitCount.One;
        serialPort.DataBits = 8;
        serialPort.Handshake = SerialHandshake.None;

        // Display configured settings
        SerialComsDisplay.Text = "Serial port configured successfully: ";
        SerialComsDisplay.Text += serialPort.BaudRate + "-";
        SerialComsDisplay.Text += serialPort.DataBits + "-";
        SerialComsDisplay.Text += serialPort.Parity.ToString() + "-";
        SerialComsDisplay.Text += serialPort.StopBits;

        // Set the RcvdText field to invoke the TextChanged callback
        // The callback launches an async Read task to wait for data
        SerialComsDisplay.Text = "Waiting for data...";

        // Create cancellation token object to close I/O operations when closing the device
        ReadCancellationTokenSource = new CancellationTokenSource();

        if (serialPort != null)
        {
            dataWriteObject = new DataWriter(serialPort.OutputStream);
            dataReaderObject = new DataReader(serialPort.InputStream);
        }

        Listen();

        startPollTimer();
    }
    catch (Exception ex)
    {
        SerialComsDisplay.Text = ex.Message;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM