public void Dispose() { Cancel(); Task.Delay(TimeSpan.FromSeconds(CancelTimeoutSeconds)); _dataReader?.DetachBuffer(); _dataReader?.DetachStream(); _dataReader?.Dispose(); _dataWriter?.DetachBuffer(); _dataWriter?.DetachStream(); _dataWriter?.Dispose(); _snocModule?.Dispose(); _readCancellationTokenSource.Dispose(); }
public void DisconnectDevice(NanoDeviceBase device) { if (FindDevice(((device as NanoDevice <NanoSerialDevice>).Device.DeviceInformation as SerialDeviceInformation).DeviceInformation.Id) != null) { EventHandlerForSerialDevice.Current.CloseDevice(); inputStreamReader?.DetachStream(); inputStreamReader?.DetachBuffer(); inputStreamReader?.Dispose(); outputStreamWriter?.DetachStream(); outputStreamWriter?.DetachBuffer(); outputStreamWriter?.Dispose(); } }
public void Dispose() { Cancel(); Task.Delay(TimeSpan.FromSeconds(CancelTimeout)); _dataReader?.DetachBuffer(); _dataReader?.DetachStream(); _dataReader?.Dispose(); _dataWriter?.DetachBuffer(); _dataWriter?.DetachStream(); _dataWriter?.Dispose(); _turrisDongle?.Dispose(); _readCancellationTokenSource.Dispose(); foreach (KeyValuePair <string, JablotronDevice> device in _jablotronDevices) { device.Value.Dispose(); } }
private async void WriteBytes(byte[] bytes) { visualizer.AddValue(bytes); if (motorCharacteristic == null) { return; } var writer = new DataWriter(); long startTime = Environment.TickCount; Console.WriteLine(startTime + " Sending " + Utils.ByteArrayToString(bytes)); writer.WriteBytes(bytes); GattCommunicationStatus status = await motorCharacteristic.WriteValueAsync(writer.DetachBuffer()); //TODO catch Exception after disconnect long endTime = Environment.TickCount; Console.WriteLine(endTime + " Status for " + Utils.ByteArrayToString(bytes) + ": " + status + ". Time: " + (endTime - startTime) + " ms"); }
private void DoWriteTag() { try { using (var writer = new DataWriter { UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE }) { Debug.WriteLine("Writing message to NFC: " + Url); writer.WriteString(Url); long id = _proximityDevice.PublishBinaryMessage("WindowsUri:WriteTag", writer.DetachBuffer()); _proximityDevice.StopPublishingMessage(id); } } catch (Exception e) { Debug.WriteLine(e.StackTrace); } }
public async void SendCommandToAllChar(IReadOnlyList<GattCharacteristic> characteristics, byte[] commandToWrite) { foreach (var characteristic in characteristics) { Debug.WriteLine("Try to write to " + CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid)); try { var writer = new DataWriter(); writer.WriteBytes(commandToWrite); await characteristic.WriteValueAsync(writer.DetachBuffer()); Debug.WriteLine("Write sucessfull"); } catch { Debug.WriteLine("Write error"); } } }
private async void CharacteristicWriteButtonInt_Click() { if (!String.IsNullOrEmpty(CharacteristicWriteValue.Text)) { var isValidValue = Int32.TryParse(CharacteristicWriteValue.Text, out int readValue); if (isValidValue) { var writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(readValue); var writeSuccessful = await WriteBufferToSelectedCharacteristicAsync(writer.DetachBuffer()); } else { rootPage.NotifyUser("Data to write has to be an int32", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("No data to write to device", NotifyType.ErrorMessage); } }
} // TransceiveAsync /// <summary> /// Extension method to SmartCardConnection class to perform a transparent exchange to the ICC /// </summary> /// <param name="connection"> /// SmartCardConnection object /// </param> /// <param name="commandData"> /// Command object to send to the ICC /// </param> /// <returns>Response received from the ICC</returns> public static async Task <byte[]> TransparentExchangeAsync(this SmartCardConnection connection, byte[] commandData) { byte[] responseData = null; ManageSessionResponse apduRes = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.StartTransparentSession, 0x00 })) as ManageSessionResponse; if (!apduRes.Succeeded) { throw new Exception("Failure to start transparent session, " + apduRes.ToString()); } using (DataWriter dataWriter = new DataWriter()) { dataWriter.WriteByte((byte)TransparentExchange.DataObjectType.Transceive); dataWriter.WriteByte((byte)commandData.Length); dataWriter.WriteBytes(commandData); TransparentExchangeResponse apduRes1 = await TransceiveAsync(connection, new TransparentExchange(dataWriter.DetachBuffer().ToArray())) as TransparentExchangeResponse; if (!apduRes1.Succeeded) { throw new Exception("Failure transceive with card, " + apduRes1.ToString()); } responseData = apduRes1.IccResponse; } ManageSessionResponse apduRes2 = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.EndTransparentSession, 0x00 })) as ManageSessionResponse; if (!apduRes2.Succeeded) { throw new Exception("Failure to end transparent session, " + apduRes2.ToString()); } return(responseData); }
private async void sendAck() { bleWriter.WriteByte(ack); await bleChannel.WriteValueAsync(bleWriter.DetachBuffer()); }
/// <summary> /// /// </summary> public MainPage() { this.InitializeComponent(); //ApplicationView.GetForCurrentView().DesiredBoundsMode ControlFlag = true; timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(500); timer.Tick += Timer_Tick; timer.Start(); TransMitter = new Guid("{e2c56db5-dffb-48d2-b060-d0f5a71096e0}"); Mobile = new Guid("{6c5df2c4-7256-4563-ba20-a2507efed9bb}"); watcher = new BluetoothLEAdvertisementWatcher(); watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(200); //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add var manufacturerData = new BluetoothLEManufacturerData(); manufacturerData.CompanyId = 0x004C; DataWriter writer = new DataWriter(); writer.WriteUInt16(0x0215); //writer.WriteUInt64(0xE2C56DB5DFFB48D2); //writer.WriteUInt64(0xB060D0F5A71096E0); writer.WriteUInt64(0x6C5DF2C472564563); writer.WriteUInt64(0xBA20A2507EFED9BB); manufacturerData.Data = writer.DetachBuffer(); //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(TransMitter); //watcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(Mobile); watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); watcher.SignalStrengthFilter.InRangeThresholdInDBm = -50; watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75; //watcher.MinSamplingInterval.Milliseconds = TimeSpan.FromMilliseconds(200); //watcher.AdvertisementFilter.Advertisement.ServiceUuids = new IList<Guid> { ""} watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(200); watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000); watcher.Stopped += Watcher_Stopped; watcher.Received += Watcher_Received; watcher.Start(); MainFrame.Navigate(typeof(NewSettingPage)); Window.Current.CoreWindow.SizeChanged += CoreWindow_SizeChanged; Window.Current.CoreWindow.VisibilityChanged += CoreWindow_VisibilityChanged; Window.Current.Closed += Current_Closed; }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public Scenario3_BackgroundWatcher() { this.InitializeComponent(); // Create and initialize a new trigger to configure it. trigger = new BluetoothLEAdvertisementWatcherTrigger(); // Configure the advertisement filter to look for the data advertised by the publisher in Scenario 2 or 4. // You need to run Scenario 2 on another Windows platform within proximity of this one for Scenario 3 to // take effect. // Unlike the APIs in Scenario 1 which operate in the foreground. This API allows the developer to register a background // task to process advertisement packets in the background. It has more restrictions on valid filter configuration. // For example, exactly one single matching filter condition is allowed (no more or less) and the sampling interval // For determining the filter restrictions programatically across APIs, use the following properties: // MinSamplingInterval, MaxSamplingInterval, MinOutOfRangeTimeout, MaxOutOfRangeTimeout // Part 1A: Configuring the advertisement filter to watch for a particular advertisement payload // First, let create a manufacturer data section we wanted to match for. These are the same as the one // created in Scenario 2 and 4. Note that in the background only a single filter pattern is allowed per trigger. var manufacturerData = new BluetoothLEManufacturerData(); #if ORG_CODE // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0xFFFE; // Finally set the data payload within the manufacturer-specific section // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian) DataWriter writer = new DataWriter(); writer.WriteUInt16(0x1234); // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception. manufacturerData.Data = writer.DetachBuffer(); // Add the manufacturer data to the advertisement filter on the trigger: trigger.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); // Part 1B: Configuring the signal strength filter for proximity scenarios // Configure the signal strength filter to only propagate events when in-range // Please adjust these values if you cannot receive any advertisement // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm // will start to be considered "in-range". trigger.SignalStrengthFilter.InRangeThresholdInDBm = -70; // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout // to determine when an advertisement is no longer considered "in-range" trigger.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75; // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm // to determine when an advertisement is no longer considered "in-range" trigger.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000); // By default, the sampling interval is set to be disabled, or the maximum sampling interval supported. // The sampling interval set to MaxSamplingInterval indicates that the event will only trigger once after it comes into range. // Here, set the sampling period to 1 second, which is the minimum supported for background. trigger.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(1000); #else // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0xFFFF; // Add the manufacturer data to the advertisement filter on the trigger: trigger.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); // Part 1B: Configuring the signal strength filter for proximity scenarios // Configure the signal strength filter to only propagate events when in-range // Please adjust these values if you cannot receive any advertisement // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm // will start to be considered "in-range". trigger.SignalStrengthFilter.InRangeThresholdInDBm = -75; // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout // to determine when an advertisement is no longer considered "in-range" trigger.SignalStrengthFilter.OutOfRangeThresholdInDBm = -90; // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm // to determine when an advertisement is no longer considered "in-range" trigger.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(3000); // By default, the sampling interval is set to be disabled, or the maximum sampling interval supported. // The sampling interval set to MaxSamplingInterval indicates that the event will only trigger once after it comes into range. // Here, set the sampling period to 1 second, which is the minimum supported for background. trigger.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(1000); #endif }
private async void NotifyClientDevices(int computedValue) { var writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(computedValue); // BT_Code: Returns a collection of all clients that the notification was attempted and the result. IReadOnlyList <GattClientNotificationResult> results = await resultCharacteristic.NotifyValueAsync(writer.DetachBuffer()); rootPage.NotifyUser($"Sent value {computedValue} to clients.", NotifyType.StatusMessage); foreach (var result in results) { // An application can iterate through each registered client that was notified and retrieve the results: // // result.SubscribedClient: The details on the remote client. // result.Status: The GattCommunicationStatus // result.ProtocolError: iff Status == GattCommunicationStatus.ProtocolError } }
public async void WriteBytes() { byte[] startBytes = { 0x55 }; byte[] strengthBytes = { 0xFF }; // visualizer.AddValue(bytes); if (lengthCharacteristic == null || startCharacteristic == null || strengthCharacteristic == null) { return; } var lengthWriter = new DataWriter(); var strengthWriter = new DataWriter(); var startWriter = new DataWriter(); long startTime = Environment.TickCount; Debug.WriteLine(startTime + " Sending " + ByteArrayToString(bytes)); lengthWriter.WriteBytes(bytes); strengthWriter.WriteBytes(strengthBytes); startWriter.WriteBytes(startBytes); GattCommunicationStatus statusLength = await lengthCharacteristic.WriteValueAsync(lengthWriter.DetachBuffer()); //TODO catch Exception after disconnect GattCommunicationStatus statusStrength = await strengthCharacteristic.WriteValueAsync(strengthWriter.DetachBuffer()); //TODO catch Exception after disconnect //GattCommunicationStatus statusStart = await //startCharacteristic.WriteValueAsync(startWriter.DetachBuffer()); //TODO catch Exception after disconnect GattCommunicationStatus status = GattCommunicationStatus.ProtocolError; // DEFAULT IST PROTOKOLL FEHLER if (statusLength == GattCommunicationStatus.Success) //&& statusStrength == GattCommunicationStatus.Success && statusStart == GattCommunicationStatus.Success) { status = GattCommunicationStatus.Success; } long endTime = Environment.TickCount; Debug.WriteLine(endTime + " Status for " + ByteArrayToString(bytes) + ": " + status + ". Time: " + (endTime - startTime) + " ms"); }
async void writeChar() { var writer = new DataWriter(); // WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle byte b = new byte(); b = (byte)textBox1.Text.ToCharArray()[0]; writer.WriteByte(b); GattCommunicationStatus result1 = await selectedCharacteristic.WriteValueAsync(writer.DetachBuffer()); if (result1 == GattCommunicationStatus.Success) { label3.Text = "Written Successfully"; button1.Enabled = true; } }
async void ConnectDevice(ulong add) { // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent. BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(add); //System.Threading.Thread.Sleep(5000); isConnected = true; // BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ble.DeviceId); //Console.WriteLine("Device Added"); //Console.ReadLine(); //GattDeviceServicesResult result = await bluetoothLeDevice; //var prslt = await bluetoothLeDevice.DeviceInformation.Pairing.PairAsync(); //System.Threading.Thread.Sleep(7000); //try 5 second lay. Guid serUuid = new Guid("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); Guid charUuid = new Guid("beb5483e-36e1-4688-b7f5-ea07361b26a8"); //IReadOnlyList<GattDeviceService> svc = bluetoothLeDevice.GattServices; GattDeviceService service = bluetoothLeDevice.GetGattService(serUuid); //Console.ReadLine(); //Console.WriteLine(String.Format(" Device Name: {0}", bluetoothLeDevice.DeviceInformation.Name)); //Console.WriteLine("Getting Characterstics"); //IReadOnlyList<GattCharacteristic> chars = service.GetAllCharacteristics(); GattCharacteristic selectedCharacteristic = service.GetCharacteristics(charUuid).FirstOrDefault(); //Console.WriteLine(chars.FirstOrDefault().Uuid); // Console.WriteLine(svc.FirstOrDefault().Uuid); // //IReadOnlyList<GattCharacteristic> chrs = svc.GetAllCharacteristics(); /* * if (result.Status == GattCommunicationStatus.Success) * { * var services = result.Services; * * // ... * }*/ //***** WRITE DATA ******* var writer = new DataWriter(); // WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle writer.WriteByte(0x78); GattCommunicationStatus result1 = await selectedCharacteristic.WriteValueAsync(writer.DetachBuffer()); if (result1 == GattCommunicationStatus.Success) { Console.WriteLine("Written Successfully"); } //***** READING DATA ******** GattReadResult result = await selectedCharacteristic.ReadValueAsync(); if (result.Status == GattCommunicationStatus.Success) { var reader = DataReader.FromBuffer(result.Value); byte[] input = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(input); Console.WriteLine(Encoding.UTF8.GetString(input)); // Utilize the data as needed } // ... }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public MainPage() { this.InitializeComponent(); // Create and initialize a new watcher instance. watcher = new BluetoothLEAdvertisementWatcher(); // Begin of watcher configuration. Configure the advertisement filter to look for the data advertised by the publisher // in Scenario 2 or 4. You need to run Scenario 2 on another Windows platform within proximity of this one for Scenario 1 to // take effect. The APIs shown in this Scenario are designed to operate only if the App is in the foreground. For background // watcher operation, please refer to Scenario 3. // Please comment out this following section (watcher configuration) if you want to remove all filters. By not specifying // any filters, all advertisements received will be notified to the App through the event handler. You should comment out the following // section if you do not have another Windows platform to run Scenario 2 alongside Scenario 1 or if you want to scan for // all LE advertisements around you. // For determining the filter restrictions programatically across APIs, use the following properties: // MinSamplingInterval, MaxSamplingInterval, MinOutOfRangeTimeout, MaxOutOfRangeTimeout // Part 1A: Configuring the advertisement filter to watch for a particular advertisement payload // First, let create a manufacturer data section we wanted to match for. These are the same as the one // created in Scenario 2 and 4. var manufacturerData = new BluetoothLEManufacturerData(); // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0xFFFE; // Finally set the data payload within the manufacturer-specific section // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian) var writer = new DataWriter(); writer.WriteUInt16(0x1234); // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception. manufacturerData.Data = writer.DetachBuffer(); // Add the manufacturer data to the advertisement filter on the watcher: watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData); // Part 1B: Configuring the signal strength filter for proximity scenarios // Configure the signal strength filter to only propagate events when in-range // Please adjust these values if you cannot receive any advertisement // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm // will start to be considered "in-range". watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70; // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout // to determine when an advertisement is no longer considered "in-range" watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75; // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm // to determine when an advertisement is no longer considered "in-range" watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000); // By default, the sampling interval is set to zero, which means there is no sampling and all // the advertisement received is returned in the Received event // End of watcher configuration. There is no need to comment out any code beyond this point. }
public async Task <bool> Connect() { UpdateStatue(TrackerStatus.Connecting, "Connecting..."); try { _service = await GattDeviceService.FromIdAsync(_deviceInfo.Id); if (_service == null) { return(false); } IReadOnlyCollection <GattCharacteristic> characteristicList = _service.GetAllCharacteristics(); foreach (var item in characteristicList) { if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_CONFIG)) { _config_characteristic = item; } else if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_PERIOD)) { _period_characteristic = item; } else if (item.Uuid == new Guid(SENSORTAG2_MOVEMENT_DATA)) { _data_characteristic = item; } } if (_config_characteristic == null || _period_characteristic == null || _data_characteristic == null) { UpdateStatue(TrackerStatus.Disconnected, "Device not support"); return(false); } DataWriter configWriter = new DataWriter(); Utility.WriteBigEndian16bit(configWriter, (ushort)(0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40)); var result = await _config_characteristic.WriteValueAsync(configWriter.DetachBuffer()); if (result == GattCommunicationStatus.Unreachable) { UpdateStatue(TrackerStatus.Disconnected, "Device unreachable"); return(false); } DataWriter periodWriter = new DataWriter(); periodWriter.WriteBytes(new byte[] { 10 }); result = await _period_characteristic.WriteValueAsync(periodWriter.DetachBuffer()); if (result == GattCommunicationStatus.Unreachable) { UpdateStatue(TrackerStatus.Disconnected, "Device unreachable"); return(false); } _bLEDevice = await BluetoothLEDevice.FromIdAsync(_deviceInfo.Id); _bLEDevice.ConnectionStatusChanged += _bLEDevice_ConnectionStatusChanged; _data_characteristic.ValueChanged += _data_characteristic_ValueChanged; result = await _data_characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); if (result == GattCommunicationStatus.Unreachable) { UpdateStatue(TrackerStatus.Disconnected, "Device unreachable"); return(false); } UpdateStatue(TrackerStatus.Connected, "Device connected. Calibrate magnetometer "); return(true); } catch { if (_service != null) { _service.Dispose(); } return(false); } }
/// <summary> /// Writes some bytes to the connected BTLE device /// </summary> /// <param name="message"></param> /// <returns></returns> public async Task WriteMessageAsync(string message) { if (!Writable) { throw new InvalidOperationException("Should not be able to write to this characteristic"); } DataWriter writer = new DataWriter(); // This currently only writes as byte. (Therefore, the entire system can only write a byte at once...) bool parseSuccess = FillDatawriterWithByte(message, writer); if (!parseSuccess) { return; } // Write buffer to device if (_characteristic.Service.Device.ConnectionStatus == BluetoothConnectionStatus.Connected) { try { if ((_characteristic.CharacteristicProperties & GattCharacteristicProperties.WriteWithoutResponse) != 0) { GattCommunicationStatus status = await _characteristic.WriteValueAsync( writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); } else { GattCommunicationStatus status = await _characteristic.WriteValueAsync( writer.DetachBuffer(), GattWriteOption.WriteWithResponse); await ReadValueAsync(); } } catch (Exception e) { /* * Error code used by device in ErrorResponse WinRT HResult in Exception GATT Definition * 0x00 E0420000 Undefined by GATT * 0x01 through 0x11 80650001 through 80650011 Defined by GATT * 0x12 through 0x7F 80651000 (E_BLUETOOTH_ATT_UNKNOWN_ERROR) Reserved by GATT * 0x7F through 0xFF E0420080 through E04200FF Application Errors * * Other errors can be found here: * http://msdn.microsoft.com/en-us/library/windows/hardware/hh450806(v=vs.85).aspx */ uint hr = (uint)e.HResult; uint highBytes = hr >> 16; uint lowBytes = hr & 0xFFFF; if (hr == 0x80651000 && hr == 0xE0420000) { Utilities.OnExceptionWithMessage(e, "Write failed, unknown error :("); } else if (highBytes == 0xE042 || (highBytes == 0x8065 && lowBytes > 0 && lowBytes < 12)) { Utilities.OnExceptionWithMessage( e, "Write failed, device ErrorResponse: 0x" + lowBytes.ToString("x")); } else { Utilities.OnException(e); } } } else { // if device isn't connected, throw an exception. Utilities.OnException(new InvalidOperationException("Cannot write to device while disconnected!")); } }
public async Task <int> WriteCharacteristic_Int(GattCharacteristic characteristic, string value) { if (characteristic == null) { return(-1); } if (!string.IsNullOrEmpty(value)) { var isValidValue = int.TryParse(value, out int readValue); if (isValidValue) { var writer = new DataWriter { ByteOrder = ByteOrder.LittleEndian }; writer.WriteInt32(readValue); return(await WriteBufferToSelectedCharacteristicAsync(characteristic, writer.DetachBuffer())); } } return(-1); }
/// <summary> /// Create a new MIDI message based on the message type and parameter(s) values, /// and send it to the chosen output device /// </summary> /// <param name="sender">Element that fired the event</param> /// <param name="e">Event arguments</param> private void sendButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { IMidiMessage midiMessageToSend = null; switch (_currentMessageType) { case MidiMessageType.NoteOff: midiMessageToSend = new MidiNoteOffMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2)), Convert.ToByte(GetParameterValue(parameter3))); break; case MidiMessageType.NoteOn: midiMessageToSend = new MidiNoteOnMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2)), Convert.ToByte(GetParameterValue(parameter3))); break; case MidiMessageType.PolyphonicKeyPressure: midiMessageToSend = new MidiPolyphonicKeyPressureMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2)), Convert.ToByte(GetParameterValue(parameter3))); break; case MidiMessageType.ControlChange: midiMessageToSend = new MidiControlChangeMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2)), Convert.ToByte(GetParameterValue(parameter3))); break; case MidiMessageType.ProgramChange: midiMessageToSend = new MidiProgramChangeMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2))); break; case MidiMessageType.ChannelPressure: midiMessageToSend = new MidiChannelPressureMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2))); break; case MidiMessageType.PitchBendChange: midiMessageToSend = new MidiPitchBendChangeMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToUInt16(GetParameterValue(parameter2))); break; case MidiMessageType.SystemExclusive: var dataWriter = new DataWriter(); var sysExMessage = sysExMessageContent.Text; var sysExMessageLength = sysExMessage.Length; // Do not send a blank SysEx message if (sysExMessageLength == 0) { return; } // SysEx messages are two characters long with 1-character space in between them // So we add 1 to the message length, so that it is perfectly divisible by 3 // The loop count tracks the number of individual message pieces int loopCount = (sysExMessageLength + 1) / 3; // Expecting a string of format "F0 NN NN NN NN.... F7", where NN is a byte in hex for (int i = 0; i < loopCount; i++) { var messageString = sysExMessage.Substring(3 * i, 2); var messageByte = Convert.ToByte(messageString, 16); dataWriter.WriteByte(messageByte); } midiMessageToSend = new MidiSystemExclusiveMessage(dataWriter.DetachBuffer()); break; case MidiMessageType.MidiTimeCode: midiMessageToSend = new MidiTimeCodeMessage(Convert.ToByte(GetParameterValue(parameter1)), Convert.ToByte(GetParameterValue(parameter2))); break; case MidiMessageType.SongPositionPointer: midiMessageToSend = new MidiSongPositionPointerMessage(Convert.ToUInt16(GetParameterValue(parameter1))); break; case MidiMessageType.SongSelect: midiMessageToSend = new MidiSongSelectMessage(Convert.ToByte(GetParameterValue(parameter1))); break; case MidiMessageType.TuneRequest: midiMessageToSend = new MidiTuneRequestMessage(); break; case MidiMessageType.TimingClock: midiMessageToSend = new MidiTimingClockMessage(); break; case MidiMessageType.Start: midiMessageToSend = new MidiStartMessage(); break; case MidiMessageType.Continue: midiMessageToSend = new MidiContinueMessage(); break; case MidiMessageType.Stop: midiMessageToSend = new MidiStopMessage(); break; case MidiMessageType.ActiveSensing: midiMessageToSend = new MidiActiveSensingMessage(); break; case MidiMessageType.SystemReset: midiMessageToSend = new MidiSystemResetMessage(); break; case MidiMessageType.None: default: return; } // Send the message _currentMidiOutputDevice.SendMessage(midiMessageToSend); NotifyUser("Message sent successfully"); }
//Write to NFC Tag async void SettingsWriteNFCTag_Click(object sender, RoutedEventArgs e) { try { ProximityDevice vProximityDevice = ProximityDevice.GetDefault(); if (vProximityDevice != null) { Nullable <bool> MessageDialogResult = null; MessageDialog MessageDialog = new MessageDialog("After this message hold your NFC tag to this device's NFC area so the tag can be written.", "TimeMe"); MessageDialog.Commands.Add(new UICommand("Continue", new UICommandInvokedHandler((cmd) => MessageDialogResult = true))); MessageDialog.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => MessageDialogResult = false))); await MessageDialog.ShowAsync(); if (MessageDialogResult == true) { Button Button = (Button)sender; string LaunchArgs = Button.Tag.ToString(); Set_NFCTags.Opacity = 0.60; Set_NFCTags.IsHitTestVisible = false; //Create 10 seconds timeout timer int TimeoutTime = 0; DispatcherTimer TimeoutTimer = new DispatcherTimer(); TimeoutTimer.Interval = TimeSpan.FromSeconds(1); TimeoutTimer.Tick += delegate { TimeoutTime++; if (TimeoutTime >= 11) { vProximityDevice = null; TimeoutTimer.Stop(); Set_NFCTags.Opacity = 1; Set_NFCTags.IsHitTestVisible = true; sp_StatusBar.Visibility = Visibility.Collapsed; } else { txt_StatusBar.Text = "Waiting on NFC tag for " + (11 - TimeoutTime).ToString() + "sec..."; sp_StatusBar.Visibility = Visibility.Visible; } }; TimeoutTimer.Start(); //Start checking for NFC tag if NFC device is active vProximityDevice.DeviceArrived += async delegate { if (vProximityDevice != null) { string WinAppId = Package.Current.Id.FamilyName + "!" + "App"; string AppMsg = LaunchArgs + "\tWindows\t" + WinAppId; using (DataWriter DataWriter = new DataWriter { UnicodeEncoding = UnicodeEncoding.Utf16LE }) { DataWriter.WriteString(AppMsg); long PublishBinaryMessage = vProximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", DataWriter.DetachBuffer()); vProximityDevice.StopPublishingMessage(PublishBinaryMessage); vProximityDevice = null; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async delegate { TimeoutTimer.Stop(); Set_NFCTags.Opacity = 1; Set_NFCTags.IsHitTestVisible = true; sp_StatusBar.Visibility = Visibility.Collapsed; await new MessageDialog("The NFC tag has successfully been written to your tag, please note that this might not work with all NFC tags due to incompatibility issues or with some tags that are locked.", "TimeMe").ShowAsync(); }); } } }; } } else { vProximityDevice = null; Nullable <bool> MessageDialogResult = null; MessageDialog MessageDialog = new MessageDialog("It seems like your device's NFC is disabled or does not support NFC, please make sure NFC is turned on before writing a new NFC tag, do you want to enable your device's NFC functionality?", "TimeMe"); MessageDialog.Commands.Add(new UICommand("Enable", new UICommandInvokedHandler((cmd) => MessageDialogResult = true))); MessageDialog.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => MessageDialogResult = false))); await MessageDialog.ShowAsync(); if (MessageDialogResult == true) { await Launcher.LaunchUriAsync(new Uri("ms-settings:proximity")); } } } catch (Exception Ex) { await new MessageDialog("NFCError: " + Ex.Message, "TimeMe").ShowAsync(); } }
static async Task TransferImage() { try { using (FileStream fs = File.Open(debugPathSource, FileMode.Open)) { byte[] img = new byte[fs.Length]; int imgLength = (int)fs.Length; // Get entire img into buffer int bytesRead = 0; int bytesToRead = imgLength; while (bytesRead < imgLength) { int n = fs.Read(img, bytesRead, bytesToRead); bytesRead += n; bytesToRead -= n; } int offset = 0; while (offset < imgLength) { var writer = new DataWriter(); // ------------------------------- // Partition whole image into PACKET_DATA_SIZE packets because the OTA // Data caharacteristic only receives <20 bytes at a time. if ((imgLength - offset) >= PACKET_DATA_SIZE) { for (int i = 0; i < PACKET_DATA_SIZE; i++) { //Console.Out.Write(img[offset]); writer.WriteByte(img[offset++]); } } // ------------------------------- // Case when the remaining bytes count are less than PACKET_DATA_SIZE and there are still // valid bytes left in the img. else if (((imgLength - offset) < PACKET_DATA_SIZE) && ((imgLength - offset) > 0)) { while (offset < imgLength) { writer.WriteByte(img[offset++]); } } // ------------------------------- // All of the data has been sent if program ever reaches here. else { break; } // ------------------------------- // Write to OTA Data characteristic var buffer = writer.DetachBuffer(); GattWriteResult result; do { result = await otaDataHandle.WriteValueWithResultAsync(buffer, GattWriteOption.WriteWithResponse); } while (result.Status != GattCommunicationStatus.Success); Thread.Sleep(200); Console.WriteLine(offset); } Console.WriteLine(offset); } } catch (Exception err) { Console.WriteLine(err.Message); } Console.WriteLine("Transfer finished."); }
/// <summary> /// Creates the SDP record that will be revealed to the Client device when pairing occurs. /// </summary> /// <param name="rfcommProvider">The RfcommServiceProvider that is being used to initialize the server</param> private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider) { App.LogService.Write("Initializing SDP attributes..."); var sdpWriter = new DataWriter(); // Write the Service Name Attribute. sdpWriter.WriteByte(BluetoothConstants.SdpServiceNameAttributeType); // The length of the UTF-8 encoded Service Name SDP Attribute. sdpWriter.WriteByte((byte)BluetoothConstants.SdpServiceName.Length); // The UTF-8 encoded Service Name value. sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; sdpWriter.WriteString(BluetoothConstants.SdpServiceName); // Set the SDP Attribute on the RFCOMM Service Provider. rfcommProvider.SdpRawAttributes.Add(BluetoothConstants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer()); }
public override void Start(AdvertisementData adData) { this.publisher.Advertisement.Flags = BluetoothLEAdvertisementFlags.ClassicNotSupported; this.publisher.Advertisement.ManufacturerData.Clear(); this.publisher.Advertisement.ServiceUuids.Clear(); if (adData.ManufacturerData != null) { using (var writer = new DataWriter()) { writer.WriteBytes(adData.ManufacturerData.Data); var md = new BluetoothLEManufacturerData(adData.ManufacturerData.CompanyId, writer.DetachBuffer()); this.publisher.Advertisement.ManufacturerData.Add(md); } } foreach (var serviceUuid in adData.ServiceUuids) { this.publisher.Advertisement.ServiceUuids.Add(serviceUuid); } this.publisher.Start(); }
/// <summary> /// Read-Write Characteristic /// </summary> /// <param name="characteristicId"></param> /// <param name="userDescription"></param> /// <returns></returns> public async Task <bool> AddReadWriteCharacteristicAsync(Guid characteristicId, string userDescription = "N/A") { await _logger.LogMessageAsync($"Adding read-write characteristic to service: description: {userDescription}, guid: {characteristicId}"); var charactericticParameters = new GattLocalCharacteristicParameters { CharacteristicProperties = GattCharacteristicProperties.WriteWithoutResponse | GattCharacteristicProperties.Read, WriteProtectionLevel = GattProtectionLevel.Plain, ReadProtectionLevel = GattProtectionLevel.Plain, UserDescription = userDescription }; var characteristicResult = await _gattServiceProvider.Service.CreateCharacteristicAsync(characteristicId, charactericticParameters); if (characteristicResult.Error != BluetoothError.Success) { await _logger.LogMessageAsync("Adding write characteristic failed"); return(false); } var characteristic = characteristicResult.Characteristic; characteristic.WriteRequested += async(sender, args) => { using (args.GetDeferral()) { // For this you need UWP bluetooth manifest enabled on app !!!!!!!! var request = await args.GetRequestAsync(); if (request == null) { return; } using (var dataReader = DataReader.FromBuffer(request.Value)) { var characteristicValue = dataReader.ReadString(request.Value.Length); if (OnChararteristicWrite != null) { OnChararteristicWrite(this, new CharacteristicEventArgs(characteristic.Uuid, characteristicValue)); } } if (request.Option == GattWriteOption.WriteWithResponse) { request.Respond(); } } }; characteristic.ReadRequested += async(sender, args) => { var deferral = args.GetDeferral(); var request = await args.GetRequestAsync(); var writer = new DataWriter(); request.RespondWithValue(writer.DetachBuffer()); deferral.Complete(); }; return(true); }
private async void Timer_Tick(ThreadPoolTimer timer) { string sensortemp; string sensorhum; double dsensortemp = 0.0; double dsensorhum = 0.0; double dco2 = 0.0; if (_cancelRequested == false) { Debug.WriteLine($"------------------------------------------------------ Blick {pocitadlo++}!!!"); try { // Check the value of the Sensor. // Temperature in Celsius is returned as a double type. Convert it to string so we can print it. sensor.Measure(); //sensortemp = sensor.TemperatureInCelsius.ToString(); dsensortemp = sensor.TemperatureInCelsius; // Same for Humidity. //sensorhum = sensor.Humidity.ToString(); dsensorhum = sensor.Humidity; // Print all of the values to the debug window. System.Diagnostics.Debug.WriteLine("Temp is " + dsensortemp + " C. And the Humidity is " + dsensorhum + "%. "); } catch (Exception ex) { // NOTE: There are frequent exceptions of the following: // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '. // This appears to be caused by the rapid frequency of writes to the GPIO // These are being swallowed here/ // If you want to see the exceptions uncomment the following: System.Diagnostics.Debug.WriteLine(ex.ToString()); } try { using (SerialDevice serialPort = await SerialDevice.FromIdAsync(dis[0].Id)) { /* Configure serial settings */ serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000); serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000); serialPort.BaudRate = 9600; /* mini UART: only standard baudrates */ serialPort.Parity = SerialParity.None; /* mini UART: no parities */ serialPort.StopBits = SerialStopBitCount.One; /* mini UART: 1 stop bit */ serialPort.DataBits = 8; /* Write a string out over serial */ //string txBuffer = "Hello Serial"; byte[] send86Buffer = { 0XFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79 }; DataWriter dataWriter = new DataWriter(); //dataWriter.WriteString(txBuffer); dataWriter.WriteBytes(send86Buffer); uint bytesWritten = await serialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer()); /* Read data in from the serial port */ const uint maxReadLength = 1024; DataReader dataReader = new DataReader(serialPort.InputStream); uint bytesToRead = await dataReader.LoadAsync(maxReadLength); byte[] recv86Buffer = new byte[bytesToRead]; dataReader.ReadBytes(recv86Buffer); //string koko = System.Convert.ToString(recv86Buffer[0],16) dco2 = recv86Buffer[2] * 256 + recv86Buffer[3]; Debug.WriteLine("Přišlo: " + System.Convert.ToString(recv86Buffer[0], 16) + ", " + System.Convert.ToString(recv86Buffer[1], 16) + ", " + System.Convert.ToString(recv86Buffer[2], 16) + ", " + System.Convert.ToString(recv86Buffer[3], 16) + ", " + System.Convert.ToString(recv86Buffer[4], 16) + ", " + System.Convert.ToString(recv86Buffer[5], 16) + ", " + System.Convert.ToString(recv86Buffer[6], 16) + ", " + System.Convert.ToString(recv86Buffer[7], 16) + ", " + System.Convert.ToString(recv86Buffer[8], 16) + "; Gas concentration = " + dco2.ToString() + " ;"); } try { var cb = new SqlConnectionStringBuilder(); cb.DataSource = "iot01.database.windows.net"; cb.UserID = "ivanj9"; cb.Password = "******"; cb.InitialCatalog = "iot01"; using (var connection = new SqlConnection(cb.ConnectionString)) { connection.Open(); String queryx = "INSERT INTO dbo.data_co2 (datum, teplota, vlhkost, co2, senzorokno, senzorosoba) VALUES (@datum, @teplota, @vlhkost, @co2, @senzorokno, @senzorosoba)"; using (SqlCommand command = new SqlCommand(queryx, connection)) { command.Parameters.AddWithValue("@datum", DateTime.Now); command.Parameters.AddWithValue("@teplota", dsensortemp); command.Parameters.AddWithValue("@vlhkost", dsensorhum); command.Parameters.AddWithValue("@co2", dco2); command.Parameters.AddWithValue("@senzorokno", 0); command.Parameters.AddWithValue("@senzorosoba", 0); //connection.Open(); int result = command.ExecuteNonQuery(); // Check Error if (result < 0) { Console.WriteLine("Error inserting data into Database!"); } } } } catch (SqlException e) { Console.WriteLine(e.ToString()); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); //throw; } } else { Debug.WriteLine("Timer cancel!!!"); timer.Cancel(); // // Indicate that the background task has completed. // deferral.Complete(); } }
/// <summary> /// Write the value to the server /// </summary> public async void WriteValue() { if (!String.IsNullOrEmpty(ValueToWrite)) { IBuffer writeBuffer = null; if (WriteType == WriteTypes.Decimal) { DataWriter writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt32(Int32.Parse(ValueToWrite)); writeBuffer = writer.DetachBuffer(); } else if (WriteType == WriteTypes.Hex) { try { // pad the value if we've received odd number of bytes if (ValueToWrite.Length % 2 == 1) { writeBuffer = GattConvert.ToIBufferFromHexString("0" + ValueToWrite); } else { writeBuffer = GattConvert.ToIBufferFromHexString(ValueToWrite); } } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); return; } } else if (WriteType == WriteTypes.UTF8) { writeBuffer = CryptographicBuffer.ConvertStringToBinary(ValueToWrite, BinaryStringEncoding.Utf8); } try { // BT_Code: Writes the value from the buffer to the characteristic. GattCommunicationStatus result = await Characteristic.Characteristic.WriteValueAsync(writeBuffer); if (result == GattCommunicationStatus.Unreachable) { NotifyUser.Insert(0, "Unable to write data - Device unreachable"); } else if (result == GattCommunicationStatus.ProtocolError) { NotifyUser.Insert(0, "Unable to write data - Protocol error"); } } catch (Exception ex) when((uint)ex.HResult == 0x80650003 || (uint)ex.HResult == 0x80070005) { // E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED or E_ACCESSDENIED // This usually happens when a device reports that it support writing, but it actually doesn't. NotifyUser.Insert(0, "Error writing to characteristic. This usually happens when a device reports that it support writing, but it actually doesn't."); } catch (Exception ex) { MessageDialog dialog = new MessageDialog(ex.Message, "Error"); await dialog.ShowAsync(); } } else { NotifyUser.Insert(0, "No data to write to device"); } }
private async Task <bool> SetSensingInterval(short interval) { var ret = false; if (DeviceInformation == null) { return(false); } // デバイスを、ペアリングしている対象の機器のIDからとってくる Device = await BluetoothLEDevice.FromIdAsync(DeviceInformation.Id); // その機器のサービスをとる var services = await Device.GetGattServicesForUuidAsync(SensingIntervalServiceUuid); if (services != null) { // そのサービスから、目的のキャラクタリスティックのコレクションをとる var characteristics = await services.Services[0].GetCharacteristicsForUuidAsync(SensingIntervalCharacteristicUuid); // コレクションには(UUID指定してるから)1個しかないはずなので、それを使う var characteristic = characteristics.Characteristics[0]; if (characteristic != null) { GattCharacteristicProperties properties = characteristic.CharacteristicProperties; // 書き込みがサポートされてるか判定 if (properties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteInt16(interval); GattCommunicationStatus r = await characteristic.WriteValueAsync(writer.DetachBuffer()); if (r == GattCommunicationStatus.Success) { Console.WriteLine("設定成功"); } } ret = true; } else { Debug.WriteLine($"[{/*MethodBase.GetCurrentMethod().Name*/0}] キャラクタリスティック取得に失敗しました({LatestDataCharacteristicUuid})"); } } else { Debug.WriteLine($"[{/*MethodBase.GetCurrentMethod().Name*/0}] サービス取得に失敗しました({SeosorServiceUuid})"); } return(ret); }
private async void BusDispatcher(IAsyncAction action) { byte[] arr; ushort crc; uint bt; SerialComm device; IBuffer buffer; Stopwatch busyCounter = new Stopwatch(); _isRunning = true; while (!action.Status.Equals(AsyncStatus.Canceled)) { if (serialComm.Count == 0) { _ARE.WaitOne(); } device = null; lock (lockObj) { _timeout = 0; if (serialComm.Count > 0) { device = serialComm.Dequeue(); } } if (device == null) { continue; } busyCounter.Restart(); arr = device.GetBuffer(); bt = 0; if (device.TxAddress != 0 && device.IsBufferValid) { //Configuration transfer request - data must be written first dataWriteObject.WriteByte(device.TxAddress); bt += await serialPort.OutputStream.WriteAsync( dataWriteObject.DetachBuffer()); dataWriteObject.WriteBytes(arr); await Task.Delay(TimeSpan.FromSeconds(1.0 / 6400)).ConfigureAwait(true); //Launch an async task to complete the write operation bt += await serialPort.OutputStream.WriteAsync( dataWriteObject.DetachBuffer()); await Task.Delay(TimeSpan.FromMilliseconds(3)).ConfigureAwait(true); } crc = BitConverter.ToUInt16(arr, arr.Length - 2); if (device.RxAddress != 0) { //Read data dataWriteObject.WriteByte(device.RxAddress); await Task.Delay(TimeSpan.FromSeconds(1.0 / 6400)).ConfigureAwait(true); bt += await serialPort.OutputStream.WriteAsync( dataWriteObject.DetachBuffer()); try { var timeoutSource = new CancellationTokenSource(14); buffer = new Windows.Storage.Streams.Buffer((uint)arr.Length); arr = (await serialPort.InputStream.ReadAsync( buffer, buffer.Capacity, InputStreamOptions.None) .AsTask(timeoutSource.Token).ConfigureAwait(true)).ToArray(); bt += (uint)arr.Length; timeoutSource.Dispose(); } catch (TaskCanceledException) { device.IsBufferValid = false; arr = null; } } if (device.TxAddress != 0 && device.RxAddress != 0 && device.IsBufferValid && arr.Length > 1 && crc != BitConverter.ToUInt16(arr, arr.Length - 2)) { lock (lockObj) serialComm.Enqueue(device); //Repeat data transmission Interlocked.Increment(ref _stats.rxLost); } else { byte result = await device.SetBuffer(arr).ConfigureAwait(true); if (result.Equals(1)) //CRC error { lock (lockObj) serialComm.Enqueue(device); //Repeat data transmission Interlocked.Increment(ref _stats.badCRC); } else if (result.Equals(2)) { Interlocked.Increment(ref _stats.txLost); } } busyCounter.Stop(); Interlocked.Increment(ref _stats.packets); Interlocked.Add(ref _ticksElapsed, bt); } }
public async void SendCommandTo1StChar(IReadOnlyList<GattCharacteristic> characteristics, byte[] commandToWrite) { var characteristic = characteristics[0]; Debug.WriteLine("Try to write to " + CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid)); try { var writer = new DataWriter(); writer.WriteBytes(commandToWrite); await characteristic.WriteValueAsync(writer.DetachBuffer()); } catch { } }
private async void ThreadedWriteData() { if (this.BlocksSent < this.MaxBlocks) { try { // Small writes if (this.SendData == null) { var small_writer = new DataWriter(); small_writer.WriteBytes(this.MetaData); await WriteGATT.WriteValueAsync(small_writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); EventHandler handler = this.OnWriteFinished; if (handler != null) { handler(null, EventArgs.Empty); } return; } // Bigger writes Array.Copy(this.MetaData, this.SendBuffer, this.MetaData.Length); if (this.SendData.Length < OAD_BLOCK_SIZE) { Array.Copy(this.SendData, 0, this.SendBuffer, 3, this.SendData.Length); } else { if (BytesSent + OAD_BLOCK_SIZE < this.SendData.Length) { this.SendBuffer[3] = 16; } else { this.SendBuffer[3] = (byte)((this.SendData.Length - this.BytesSent) + 2); } this.SendBuffer[4] = (byte)this.MaxBlocks; this.SendBuffer[5] = (byte)this.BlocksSent; Array.Copy(this.SendData, BytesSent, this.SendBuffer, 6, this.SendBuffer[3] - 2); } var writer = new DataWriter(); writer.WriteBytes(this.SendBuffer); var result = await WriteGATT.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); // throw an error? if (result != GattCommunicationStatus.Success) { return; } this.BlocksSent += 1; this.BytesSent += OAD_BLOCK_SIZE; WriteToKeyboard(); } catch (Exception ex) { Debug.WriteLine(ex); EventHandler handler = this.OnWriteFailed; if (handler != null) { handler(ex, EventArgs.Empty); } } } else { EventHandler handler = this.OnWriteFinished; if (handler != null) { handler(null, EventArgs.Empty); } } }
public async void SendMotorCommand(Boolean on, int tilt, int forward, int turn, int up, float scale) { var characteristics = _service.GetCharacteristics(RollingSpiderCharacteristicUuids.Parrot_PowerMotors); var characteristic = characteristics[0]; var writer = new DataWriter(); try { writer.WriteByte(2); writer.WriteByte((byte)_motorCounter); writer.WriteByte(2); writer.WriteByte(0); writer.WriteByte(2); writer.WriteByte(0); if (on) { writer.WriteByte(1); } else { writer.WriteByte(0); } // is byte casting necessary??? writer.WriteByte((byte)(tilt & 0xFF)); writer.WriteByte((byte)(forward & 0xFF)); writer.WriteByte((byte)(turn & 0xFF)); writer.WriteByte((byte)(up & 0xFF)); //writer.WriteDouble(scale); // well, but I need different endian :( await characteristic.WriteValueAsync(writer.DetachBuffer()); } catch (IOException e) { Debug.WriteLine(e); } //var gattTransaction = new GattReliableWriteTransaction(); //gattTransaction.WriteValue(characteristic, writer.DetachBuffer()); //var status = await gattTransaction.CommitAsync(); //switch (status) //{ // case GattCommunicationStatus.Success: // AddLogAction("Writing to your device OK !"); // break; // case GattCommunicationStatus.Unreachable: // AddLogAction("Writing to your device Failed !"); // break; //} }
public override void Write(byte[] buffer, int offset, int count) { try { Windows.Storage.Streams.Buffer buffer1 = new Windows.Storage.Streams.Buffer((uint)count); byte[] numArray; if (offset == 0 && count == buffer.Length) { numArray = buffer; } else { numArray = new byte[count]; Array.Copy((Array)buffer, offset, (Array)numArray, 0, count); } DataWriter dataWriter = new DataWriter(); dataWriter.WriteBytes(numArray); WindowsRuntimeSystemExtensions.AsTask <uint, uint>(this.backend.WriteAsync(dataWriter.DetachBuffer())).Wait(this.writeTimeout); } catch (Exception ex) { throw FileStream.RethrowException(ex); } }