Guest User

Full code

a guest
Apr 29th, 2016
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.91 KB | None | 0 0
  1.  using System;
  2. using Windows.UI.Xaml;
  3. using Windows.UI.Xaml.Controls;
  4. using System.Threading;
  5. using Windows.Devices.SerialCommunication;
  6. using System.Collections.ObjectModel;
  7. using Windows.Storage.Streams;
  8. using Windows.Devices.Enumeration;
  9. using System.Threading.Tasks;
  10.  
  11. namespace Serial_Communication_Universal
  12. {
  13.     public sealed partial class MainPage : Page
  14.     {
  15.         private SerialDevice serialPort = null;
  16.         DataWriter dataWriteObject = null;
  17.         DataReader dataReaderObject = null;
  18.  
  19.         private ObservableCollection<DeviceInformation> listOfDevices;
  20.         private CancellationTokenSource ReadCancellationTokenSource;
  21.  
  22.         public MainPage()
  23.         {
  24.             this.InitializeComponent();
  25.             sendTextBox.IsEnabled = false;
  26.             sendButton.IsEnabled = false;
  27.             reciveTextBox.IsEnabled = false;
  28.             disconnectButton.IsEnabled = false;
  29.             listOfDevices = new ObservableCollection<DeviceInformation>();
  30.             getAvailPorts();
  31.         }
  32.  
  33.         private async void getAvailPorts()
  34.         {
  35.  
  36.                 string aqs = SerialDevice.GetDeviceSelector();
  37.                 var dis = await DeviceInformation.FindAllAsync(aqs);
  38.  
  39.                 for (int i = 0; i < dis.Count; i++)
  40.                 {
  41.                     listOfDevices.Add(dis[i]);
  42.                 }
  43.  
  44.                 DeviceListSource.Source = listOfDevices;
  45.                 baudListBox.SelectedIndex = -1;
  46.         }
  47.  
  48.         private async void connectButton_Click(object sender, RoutedEventArgs e)
  49.         {
  50.             var selection = baudListBox.SelectedItem;
  51.  
  52.             DeviceInformation entry = (DeviceInformation)selection;
  53.  
  54.  
  55.             try
  56.             {
  57.                 serialPort = await SerialDevice.FromIdAsync(entry.Id);
  58.  
  59.                 connectButton.IsEnabled = false;
  60.  
  61.                 serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
  62.                 serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
  63.                 serialPort.BaudRate = 9600;
  64.                 serialPort.Parity = SerialParity.None;
  65.                 serialPort.StopBits = SerialStopBitCount.One;
  66.                 serialPort.DataBits = 8;
  67.                 serialPort.Handshake = SerialHandshake.None;
  68.  
  69.                 ReadCancellationTokenSource = new CancellationTokenSource();
  70.  
  71.                 sendButton.IsEnabled = true;
  72.                 sendTextBox.IsEnabled = true;
  73.                 sendButton.IsEnabled = true;
  74.                 reciveTextBox.IsEnabled = true;
  75.                 disconnectButton.IsEnabled = true;
  76.  
  77.                 Listen();
  78.             }
  79.             catch (Exception ex)
  80.             {
  81.                 connectButton.IsEnabled = true;
  82.                 sendButton.IsEnabled = false;
  83.             }
  84.  
  85.         }
  86.  
  87.         private async void Listen()
  88.         {
  89.             try
  90.             {
  91.                 if (serialPort != null)
  92.                 {
  93.                     dataReaderObject = new DataReader(serialPort.InputStream);
  94.  
  95.                     while (true)
  96.                     {
  97.                         await ReadAsync(ReadCancellationTokenSource.Token);
  98.                     }
  99.                 }
  100.             }
  101.             catch (Exception ex)
  102.             {
  103.                 if (ex.GetType().Name == "TaskCanceledException")
  104.                 {
  105.                     CloseDevice();
  106.                 }
  107.             }
  108.             finally
  109.             {
  110.                 if (dataReaderObject != null)
  111.                 {
  112.                     dataReaderObject.DetachStream();
  113.                     dataReaderObject = null;
  114.                 }
  115.             }
  116.         }
  117.  
  118.         private async Task ReadAsync(CancellationToken cancellationToken)
  119.         {
  120.             Task<UInt32> loadAsyncTask;
  121.  
  122.             uint ReadBufferLength = 1024;
  123.  
  124.             cancellationToken.ThrowIfCancellationRequested();
  125.  
  126.             dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
  127.  
  128.             loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
  129.  
  130.             UInt32 bytesRead = await loadAsyncTask;
  131.             if (bytesRead > 0)
  132.             {
  133.                 reciveTextBox.Text = dataReaderObject.ReadString(bytesRead);
  134.             }
  135.         }
  136.  
  137.         private void CloseDevice()
  138.         {
  139.             if (serialPort != null)
  140.             {
  141.                 serialPort.Dispose();
  142.             }
  143.             serialPort = null;
  144.  
  145.             connectButton.IsEnabled = true;
  146.             sendButton.IsEnabled = false;
  147.             reciveTextBox.Text = "";
  148.             listOfDevices.Clear();
  149.         }
  150.  
  151.         private async void sendButton_Click(object sender, RoutedEventArgs e)
  152.         {
  153.             try
  154.             {
  155.                     dataWriteObject = new DataWriter(serialPort.OutputStream);
  156.  
  157.                     await WriteAsync();
  158.             }
  159.             catch (Exception ex)
  160.             {
  161.             }
  162.             finally
  163.             {
  164.                 if (dataWriteObject != null)
  165.                 {
  166.                     dataWriteObject.DetachStream();
  167.                     dataWriteObject = null;
  168.                 }
  169.             }
  170.         }
  171.  
  172.         private async Task WriteAsync()
  173.         {
  174.             Task<UInt32> storeAsyncTask;
  175.  
  176.             if (sendTextBox.Text.Length != 0)
  177.             {
  178.                 dataWriteObject.WriteString(sendTextBox.Text);
  179.  
  180.                 storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
  181.  
  182.                 UInt32 bytesWritten = await storeAsyncTask;
  183.                 if (bytesWritten > 0)
  184.                 {
  185.                 }
  186.                 sendTextBox.Text = "";
  187.             }
  188.             else
  189.             {
  190.             }
  191.         }
  192.  
  193.         private void disconnectButton_Click(object sender, RoutedEventArgs e)
  194.         {
  195.             try
  196.             {
  197.                 CancelReadTask();
  198.                 CloseDevice();
  199.                 getAvailPorts();
  200.             }
  201.             catch (Exception ex)
  202.             {
  203.             }
  204.         }
  205.  
  206.         private void CancelReadTask()
  207.         {
  208.             if (ReadCancellationTokenSource != null)
  209.             {
  210.                 if (!ReadCancellationTokenSource.IsCancellationRequested)
  211.                 {
  212.                     ReadCancellationTokenSource.Cancel();
  213.                 }
  214.             }
  215.         }
  216.  
  217.         private void reciveTextBox_TextChanged(object sender, TextChangedEventArgs e)
  218.         {
  219.             if(scrollCheckBox.IsChecked == true)
  220.             {
  221.                 reciveTextBox.SelectionStart = reciveTextBox.Text.Length;
  222.             }
  223.         }
  224.  
  225.         private void refreshButton_Click(object sender, RoutedEventArgs e)
  226.         {
  227.             getAvailPorts();
  228.         }
  229.  
  230.         private void mainPage_Loaded(object sender, RoutedEventArgs e)
  231.         {
  232.  
  233.         }
  234.  
  235.         private void RefButton_Click(object sender, RoutedEventArgs e)
  236.         {
  237.             Listen();
  238.         }
  239.     }
  240. }
Add Comment
Please, Sign In to add comment