Advertisement
Quantumzblue

C# Uart terminal & HTTP post

Dec 18th, 2015
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.73 KB | None | 0 0
  1. // Copyright (c) Microsoft. All rights reserved.
  2. using System;
  3. using System.Collections.ObjectModel;
  4. using Windows.UI.Xaml;
  5. using Windows.UI.Xaml.Controls;
  6. using Windows.Devices.Enumeration;
  7. using Windows.Devices.SerialCommunication;
  8. using Windows.Storage.Streams;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Collections.Specialized;
  12. using System.Net;
  13.  
  14. namespace SerialSample
  15. {
  16. public sealed partial class MainPage : Page
  17. {
  18.  
  19. private SerialDevice serialPort = null;
  20. DataWriter dataWriteObject = null;
  21. DataReader dataReaderObject = null;
  22.  
  23. private ObservableCollection<DeviceInformation> listOfDevices;
  24. private CancellationTokenSource ReadCancellationTokenSource;
  25.  
  26. public MainPage()
  27. {
  28. this.InitializeComponent();
  29. comPortInput.IsEnabled = false;
  30. sendTextButton.IsEnabled = false;
  31. listOfDevices = new ObservableCollection<DeviceInformation>();
  32. ListAvailablePorts();
  33. }
  34.  
  35.  
  36. private async void ListAvailablePorts()
  37. {
  38. try
  39. {
  40. string aqs = SerialDevice.GetDeviceSelector();
  41. var dis = await DeviceInformation.FindAllAsync(aqs);
  42.  
  43. status.Text = "Select a device and connect";
  44.  
  45. for (int i = 0; i < dis.Count; i++)
  46. {
  47. listOfDevices.Add(dis[i]);
  48. }
  49.  
  50. DeviceListSource.Source = listOfDevices;
  51. comPortInput.IsEnabled = true;
  52. ConnectDevices.SelectedIndex = -1;
  53. }
  54. catch (Exception ex)
  55. {
  56. status.Text = ex.Message;
  57. }
  58. }
  59.  
  60.  
  61. private async void comPortInput_Click(object sender, RoutedEventArgs e)
  62. {
  63. var selection = ConnectDevices.SelectedItems;
  64.  
  65. if (selection.Count <= 0)
  66. {
  67. status.Text = "Select a device and connect";
  68. return;
  69. }
  70.  
  71. DeviceInformation entry = (DeviceInformation)selection[0];
  72.  
  73. try
  74. {
  75. serialPort = await SerialDevice.FromIdAsync(entry.Id);
  76.  
  77. // Disable the 'Connect' button
  78. comPortInput.IsEnabled = false;
  79.  
  80. // Configure serial settings
  81. serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
  82. serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
  83. serialPort.BaudRate = 9600;
  84. serialPort.Parity = SerialParity.None;
  85. serialPort.StopBits = SerialStopBitCount.One;
  86. serialPort.DataBits = 8;
  87.  
  88. // Display configured settings
  89. status.Text = "Serial port configured successfully!\n ----- Properties ----- \n";
  90. status.Text += "BaudRate: " + serialPort.BaudRate.ToString() + "\n";
  91. status.Text += "DataBits: " + serialPort.DataBits.ToString() + "\n";
  92. status.Text += "Handshake: " + serialPort.Handshake.ToString() + "\n";
  93. status.Text += "Parity: " + serialPort.Parity.ToString() + "\n";
  94. status.Text += "StopBits: " + serialPort.StopBits.ToString() + "\n";
  95.  
  96. // Set the RcvdText field to invoke the TextChanged callback
  97. // The callback launches an async Read task to wait for data
  98. rcvdText.Text = "Waiting for data...";
  99.  
  100. // Create cancellation token object to close I/O operations when closing the device
  101. ReadCancellationTokenSource = new CancellationTokenSource();
  102.  
  103. // Enable 'WRITE' button to allow sending data
  104. sendTextButton.IsEnabled = true;
  105. }
  106. catch (Exception ex)
  107. {
  108. status.Text = ex.Message;
  109. comPortInput.IsEnabled = true;
  110. sendTextButton.IsEnabled = false;
  111. }
  112. }
  113.  
  114.  
  115. private async void sendTextButton_Click(object sender, RoutedEventArgs e)
  116. {
  117. try
  118. {
  119. if (serialPort != null)
  120. {
  121. // Create the DataWriter object and attach to OutputStream
  122. dataWriteObject = new DataWriter(serialPort.OutputStream);
  123.  
  124. //Launch the WriteAsync task to perform the write
  125. await WriteAsync();
  126. }
  127. else
  128. {
  129. status.Text = "Select a device and connect";
  130. }
  131. }
  132. catch (Exception ex)
  133. {
  134. status.Text = "sendTextButton_Click: " + ex.Message;
  135. }
  136. finally
  137. {
  138. // Cleanup once complete
  139. if (dataWriteObject != null)
  140. {
  141. dataWriteObject.DetachStream();
  142. dataWriteObject = null;
  143. }
  144. }
  145. }
  146.  
  147.  
  148. private async Task WriteAsync()
  149. {
  150. Task<UInt32> storeAsyncTask;
  151.  
  152. if (sendText.Text.Length != 0)
  153. {
  154. // Load the text from the sendText input text box to the dataWriter object
  155. dataWriteObject.WriteString(sendText.Text);
  156.  
  157. // Launch an async task to complete the write operation
  158. storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
  159.  
  160. UInt32 bytesWritten = await storeAsyncTask;
  161. if (bytesWritten > 0)
  162. {
  163. status.Text = sendText.Text + '\n';
  164. status.Text += "Bytes written successfully!";
  165. }
  166. sendText.Text = "";
  167. }
  168. else
  169. {
  170. status.Text = "Enter the text you want to write and then click on 'WRITE'";
  171. }
  172. }
  173.  
  174.  
  175. private async void rcvdText_TextChanged(object sender, TextChangedEventArgs e)
  176. {
  177. try
  178. {
  179. if (serialPort != null)
  180. {
  181. dataReaderObject = new DataReader(serialPort.InputStream);
  182. await ReadAsync(ReadCancellationTokenSource.Token);
  183. }
  184. }
  185. catch (Exception ex)
  186. {
  187. if (ex.GetType().Name == "TaskCanceledException")
  188. {
  189. status.Text = "Reading task was cancelled, closing device and cleaning up";
  190. CloseDevice();
  191. }
  192. else
  193. {
  194. status.Text = ex.Message;
  195. }
  196. }
  197. finally
  198. {
  199. // Cleanup once complete
  200. if (dataReaderObject != null)
  201. {
  202. dataReaderObject.DetachStream();
  203. dataReaderObject = null;
  204. }
  205. }
  206. }
  207.  
  208.  
  209. private async Task ReadAsync(CancellationToken cancellationToken)
  210. {
  211. Task<UInt32> loadAsyncTask;
  212.  
  213. uint ReadBufferLength = 1024;
  214.  
  215. // If task cancellation was requested, comply
  216. cancellationToken.ThrowIfCancellationRequested();
  217.  
  218. // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
  219. dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
  220.  
  221. // Create a task object to wait for data on the serialPort.InputStream
  222. loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
  223.  
  224. // Launch the task and wait
  225. UInt32 bytesRead = await loadAsyncTask;
  226. if (bytesRead > 0)
  227. {
  228. //Send data to send via HTTP protocal
  229. string UID = dataReaderObject.ReadString(bytesRead);
  230. rcvdText.Text = UID;
  231. status.Text = "\nBytes read successfully!";
  232. using (var wb = new WebClient())
  233.  
  234. {
  235. var data = new NameValueCollection();
  236. data["field1"] = UID;
  237. var response = wb.UploadValues("http://127.0.0.1/myprocessingscript.php", "POST", data);
  238.  
  239.  
  240.  
  241.  
  242. }
  243. }
  244. }
  245.  
  246.  
  247. private void CancelReadTask()
  248. {
  249. if (ReadCancellationTokenSource != null)
  250. {
  251. if (!ReadCancellationTokenSource.IsCancellationRequested)
  252. {
  253. ReadCancellationTokenSource.Cancel();
  254. }
  255. }
  256. }
  257.  
  258.  
  259. private void CloseDevice()
  260. {
  261. if (serialPort != null)
  262. {
  263. serialPort.Dispose();
  264. }
  265. serialPort = null;
  266.  
  267. comPortInput.IsEnabled = true;
  268. sendTextButton.IsEnabled = false;
  269. rcvdText.Text = "";
  270. listOfDevices.Clear();
  271. }
  272.  
  273.  
  274. private void closeDevice_Click(object sender, RoutedEventArgs e)
  275. {
  276. try
  277. {
  278. status.Text = "";
  279. CancelReadTask();
  280. CloseDevice();
  281. ListAvailablePorts();
  282. }
  283. catch (Exception ex)
  284. {
  285. status.Text = ex.Message;
  286. }
  287. }
  288.  
  289.  
  290. }
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement