/// <summary> /// SET_LINE_CODING CDC request. /// </summary> /// <param name="index">Interface index.</param> /// <param name="dteRate">Data terminal rate, in bits per second.</param> /// <param name="charFormat">Stop bits.</param> /// <param name="parityType">Parity.</param> /// <param name="dataBits">Data bits.</param> /// <returns> /// The result of Task contains a length of bytes actually sent to the serial port. /// </returns> private Task <uint> SetLineCoding( uint index, uint dteRate, byte charFormat, byte parityType, byte dataBits ) { // SetLineCoding var writer = new Windows.Storage.Streams.DataWriter(); writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; writer.WriteUInt32(dteRate); writer.WriteByte(charFormat); writer.WriteByte(parityType); writer.WriteByte(dataBits); var buffer = writer.DetachBuffer(); var requestType = new UsbControlRequestType(); requestType.AsByte = RequestType.Set; return(UsbControlRequestForSet( index, requestType, RequestCode.SetLineCoding, 0, buffer)); }
public async Task TurnOnSensor() { Debug.WriteLine("Begin turn on sensor: " + SensorIndex.ToString()); // Turn on sensor if (SensorIndex >= 0 && SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && SensorIndex != SensorIndexes.REGISTERS) { if (Configuration != null) { if (Configuration.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); // Special value for Gyroscope to enable all 3 axes ////////if (sensor == GYROSCOPE) //////// writer.WriteByte((Byte)0x07); ////////else // Special value for Gyroscope to enable all 3 axes if (SensorIndex == SensorIndexes.MOVEMENT) { byte[] bytes = new byte[] { 0x7f, 0x00 }; writer.WriteBytes(bytes); } else { writer.WriteByte((Byte)0x01); } var status = await Configuration.WriteValueAsync(writer.DetachBuffer()); } } } Debug.WriteLine("End turn on sensor: " + SensorIndex.ToString()); }
async void InitializeBluetooth() { try { var service_id = RfcommServiceId.FromUuid(Guid.Parse("ff1477c2-7265-4d55-bb08-c3c32c6d635c")); provider = await RfcommServiceProvider.CreateAsync(service_id); StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindServiceNameAsync( provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // InitializeServiceSdpAttributes var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); writer.WriteUInt32(SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); provider.StartAdvertising(listener, true); } catch (Exception error) { Debug.WriteLine(error.ToString()); } }
public async Task TurnOffSensor() { try { Debug.WriteLine("Begin turn off sensor: " + SensorIndex.ToString()); // Turn on sensor if (SensorIndex >= 0 && SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && SensorIndex != SensorIndexes.REGISTERS) { if (Configuration != null) { if (Configuration.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); if (SensorIndex == SensorIndexes.MOVEMENT) { byte[] bytes = new byte[] { 0x00, 0x00 };//Fixed writer.WriteBytes(bytes); } else { writer.WriteByte((Byte)0x00); } var status = await Configuration.WriteValueAsync(writer.DetachBuffer()); } } } } catch (Exception ex) { Debug.WriteLine("Error: TurnOffSensor(): " + SensorIndex.ToString() + " " + ex.Message); } Debug.WriteLine("End turn off sensor: " + SensorIndex.ToString()); }
static void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { var writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); }
/// <summary> /// Sends a broadcast message searching for available Webservices /// </summary> private async Task SendMessage(DatagramSocket socket) { HostName hostName = new HostName("255.255.255.255"); // to all listeners using (var stream = await socket.GetOutputStreamAsync(hostName, m_SendPort.ToString())) { using (var writer = new Windows.Storage.Streams.DataWriter(stream)) { // <Command>;<Timeout> string sendstr = String.Format("{0};{1}", "OnVifUniversal.SEARCHWS", this.m_timeOut); var data = Encoding.UTF8.GetBytes(sendstr); writer.WriteBytes(data); writer.WriteByte(0); // String 0 await writer.StoreAsync(); } } }
private void radioButtonDataFormat_Checked(object sender, RoutedEventArgs e) { if (sender.Equals(this.radioButtonAscii)) { var binary = this.textBoxReadBulkInLogger.Text; var separator = new String[1]; separator[0] = " "; var byteArray = binary.Split(separator, StringSplitOptions.None); // Binary to Unicode. uint strlen = 0; var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onebyte in byteArray) { if (onebyte.Length < 2) { continue; } writer.WriteByte(byte.Parse(onebyte, System.Globalization.NumberStyles.HexNumber)); strlen++; } var reader = Windows.Storage.Streams.DataReader.FromBuffer(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = reader.ReadString(strlen); } else if (sender.Equals(this.radioButtonBinary)) { var ascii = this.textBoxReadBulkInLogger.Text; // Unicode to ASCII. var chars = ascii.ToCharArray(0, ascii.Length); var writer = new Windows.Storage.Streams.DataWriter(); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; foreach (var onechar in chars) { writer.WriteByte((byte)onechar); } var str = Util.BinaryBufferToBinaryString(writer.DetachBuffer()); this.textBoxReadBulkInLogger.Text = str; } }
private async void findDevices() { //var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess)); var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("19B10000-E8F2-537E-4F6C-D104768A1214"))); if (devices.Count == 0) { textBox.Text = "Devices not found!"; return; } //Connect to the service var service = await GattDeviceService.FromIdAsync(devices[0].Id); if (service == null) { return; } //Obtain the characteristic we want to interact with //var characteristics = service.GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(0x2A00)); var characteristics = service.GetCharacteristics(new Guid("19B10001-E8F2-537E-4F6C-D104768A1214")); characteristic = characteristics[0]; //Read the value var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte(12); await characteristic.WriteValueAsync(writer.DetachBuffer()); var valueBytes = (await characteristic.ReadValueAsync()).Value.ToArray(); var value = await characteristic.ReadValueAsync(); //Convert to string //var deviceName = System.Text.Encoding.UTF8.GetString(deviceNameBytes, 0, deviceNameBytes.Length); characteristic.ValueChanged += Characteristic_ValueChanged; await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); textBox.Text = valueBytes[0].ToString(); }
private void buttonWriteBulkOut_Click(object sender, RoutedEventArgs e) { if (this.SerialPortInfo != null) { var dataToWrite = this.textBoxDataToWrite.Text; var dispatcher = this.Dispatcher; ((Action)(async() => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() => { // Unicode to ASCII. var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[dataToWrite.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(dataToWrite.ToCharArray(), 0, dataToWrite.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); var isChecked = checkBoxSendNullTerminateCharToBulkOut.IsChecked; if (isChecked.HasValue && isChecked.Value == true) { writer.WriteByte(0x00); // NUL } var buffer = writer.DetachBuffer(); await this.SerialPortInfo.Port.Write(buffer, 0, buffer.Length); var temp = this.textBoxWriteLog.Text; temp += "Write completed: \"" + dataToWrite + "\" (" + buffer.Length.ToString() + " bytes)\n"; this.textBoxWriteLog.Text = temp; this.textBoxDataToWrite.Text = ""; })); } )).Invoke(); } }
private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e) { // Unicode to ASCII. String textToSend = this.textBoxForLoopback.Text; var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[textToSend.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); writer.WriteByte(0x00); // NUL var buffer = writer.DetachBuffer(); this.buttonLoopbackTest.IsEnabled = false; this.buttonStopLoopback.IsEnabled = true; SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage); var dispatcher = this.Dispatcher; ((Action)(async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { // serialport1 to serialport2 var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length); readBuffer.Length = buffer.Length; var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask(); var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] {writeTask, readTask}); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } var isSame = Util.CompareTo(buffer, readBuffer) == 0; String statusMessage = ""; if (isSame) { statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. "; } else { statusMessage += "Loopback failed: CDC device 1 to CDC device 2. "; } // serialport2 to serialport1 readBuffer.Length = buffer.Length; writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask(); readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask }); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } isSame = Util.CompareTo(buffer, readBuffer) == 0; if (isSame) { statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. "; } else { statusMessage += "Loopback failed: CDC device 2 to CDC device 1. "; } this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage); })); } )).Invoke(); }
public void toggleAllDigitalPinsV2(bool setPinsHigh) { //a DataWriter object uses an IBuffer as its backing storage //we'll write our data to this object and detach the buffer to invoke sendSysex() Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(); //we're defining our own command, so we're free to encode it how we want. //let's send a '1' if we want the pins HIGH, and a 0 for LOW writer.WriteByte((byte)(setPinsHigh ? 1 : 0)); //invoke the sendSysex command with ALL_PINS_COMMAND and our data payload as an IBuffer //firmata.@lock(); firmata.sendSysex(ALL_PINS_COMMAND, writer.DetachBuffer()); //firmata.@unlock(); }
/// <summary> /// SET_LINE_CODING CDC request. /// </summary> /// <param name="index">Interface index.</param> /// <param name="dteRate">Data terminal rate, in bits per second.</param> /// <param name="charFormat">Stop bits.</param> /// <param name="parityType">Parity.</param> /// <param name="dataBits">Data bits.</param> /// <returns> /// The result of Task contains a length of bytes actually sent to the serial port. /// </returns> private Task<uint> SetLineCoding( uint index, uint dteRate, byte charFormat, byte parityType, byte dataBits ) { // SetLineCoding var writer = new Windows.Storage.Streams.DataWriter(); writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; writer.WriteUInt32(dteRate); writer.WriteByte(charFormat); writer.WriteByte(parityType); writer.WriteByte(dataBits); var buffer = writer.DetachBuffer(); var requestType = new UsbControlRequestType(); requestType.AsByte = RequestType.Set; return UsbControlRequestForSet( index, requestType, RequestCode.SetLineCoding, 0, buffer); }
private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e) { // Unicode to ASCII. String textToSend = this.textBoxForLoopback.Text; var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[textToSend.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); writer.WriteByte(0x00); // NUL var buffer = writer.DetachBuffer(); this.buttonLoopbackTest.IsEnabled = false; this.buttonStopLoopback.IsEnabled = true; SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage); var dispatcher = this.Dispatcher; ((Action)(async() => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() => { // serialport1 to serialport2 var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length); readBuffer.Length = buffer.Length; var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask(); var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask }); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } var isSame = Util.CompareTo(buffer, readBuffer) == 0; String statusMessage = ""; if (isSame) { statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. "; } else { statusMessage += "Loopback failed: CDC device 1 to CDC device 2. "; } // serialport2 to serialport1 readBuffer.Length = buffer.Length; writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask(); readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask(); try { await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask }); readBuffer.Length = (uint)readTask.Result; } catch (System.OperationCanceledException) { // canceled. SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage); this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; return; } finally { this.cancelTokenSrcOpRead = null; writeTask.AsAsyncAction().Cancel(); // just in case. readTask.AsAsyncAction().Cancel(); // just in case. } isSame = Util.CompareTo(buffer, readBuffer) == 0; if (isSame) { statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. "; } else { statusMessage += "Loopback failed: CDC device 2 to CDC device 1. "; } this.buttonLoopbackTest.IsEnabled = true; this.buttonStopLoopback.IsEnabled = false; SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage); })); } )).Invoke(); }
private void buttonWriteBulkOut_Click(object sender, RoutedEventArgs e) { if (this.SerialPortInfo != null) { var dataToWrite = this.textBoxDataToWrite.Text; var dispatcher = this.Dispatcher; ((Action)(async () => { await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () => { // Unicode to ASCII. var encoder = System.Text.Encoding.UTF8.GetEncoder(); var utf8bytes = new byte[dataToWrite.Length]; int bytesUsed, charsUsed; bool completed; encoder.Convert(dataToWrite.ToCharArray(), 0, dataToWrite.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed); var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(utf8bytes); var isChecked = checkBoxSendNullTerminateCharToBulkOut.IsChecked; if (isChecked.HasValue && isChecked.Value == true) { writer.WriteByte(0x00); // NUL } var buffer = writer.DetachBuffer(); await this.SerialPortInfo.Port.Write(buffer, 0, buffer.Length); var temp = this.textBoxWriteLog.Text; temp += "Write completed: \"" + dataToWrite + "\" (" + buffer.Length.ToString() + " bytes)\n"; this.textBoxWriteLog.Text = temp; this.textBoxDataToWrite.Text = ""; })); } )).Invoke(); } }