private void OnWriteableTagArrived(ProximityDevice sender, ProximityMessage message) { var dataWriter = new DataWriter(); dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE; string appLauncher = string.Format(@"mywaiter:MainPage?source=3"); dataWriter.WriteString(appLauncher); pubId = sender.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer()); }
/// <summary> /// 加密 /// </summary> /// <param name="toEncrypt"></param> /// <param name="bufferkey"></param> /// <returns></returns> public static string Encrypt(string toEncrypt) { SymmetricKeyAlgorithmProvider aesCbcPkcs7 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); var dataWriter = new DataWriter(); dataWriter.WriteBytes(new byte[] { 65, 69, 87, 65, 49, 50, 94, 64, 35, 77, 65, 87, 40, 0, 0, 0 }); CryptographicKey key = aesCbcPkcs7.CreateSymmetricKey(dataWriter.DetachBuffer()); byte[] plainText = Encoding.UTF8.GetBytes(toEncrypt); byte[] cipherText = CryptographicEngine.Encrypt( key, plainText.AsBuffer(), dataWriter.DetachBuffer()).ToArray(); return Convert.ToBase64String(cipherText, 0, cipherText.Length); }
private async Task WriteBlecOmmand(string command) { try { _commandExecuting = true; BluetoothLEDevice oygenBluetoothLeDevice = null; GattCharacteristic writeCharacteristics = null; oygenBluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(0x000780067cf1); var srv = oygenBluetoothLeDevice.GattServices.FirstOrDefault( gs => gs.Uuid.ToString().Equals("2ac94b65-c8f4-48a4-804a-c03bc6960b80")); Debug.WriteLine(oygenBluetoothLeDevice.Name); writeCharacteristics = srv .GetAllCharacteristics() .FirstOrDefault(ch => ch.Uuid.ToString().Equals("50e03f22-b496-4a73-9e85-335482ed4b12")); var writer = new DataWriter(); writer.WriteString(command + "\n"); await writeCharacteristics.WriteValueAsync(writer.DetachBuffer()); } catch (Exception ex) { Debug.WriteLine("Bluetooth Problem."); Debug.WriteLine(ex.Message); } }
private async void ButtonAction2_Click(object sender, RoutedEventArgs e) { DevicesInformation = string.Empty; foreach (var rsCharacteristic in _dicCharacteristics) { DevicesInformation += $" Try to write to {rsCharacteristic.Value.CharName}{Environment.NewLine}"; bool writeOk = true; try { var charToTest = rsCharacteristic.Value.Characteristic; byte[] arr = { 4, 1, 2, 0, 1, 0 }; var writer = new DataWriter(); writer.WriteBytes(arr); await charToTest.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - OK{Environment.NewLine}"; } catch { DevicesInformation += $" - ERROR{Environment.NewLine}"; writeOk = false; } var msg = $"{rsCharacteristic.Value.CharName}, {writeOk}, {rsCharacteristic.Value.Characteristic.CharacteristicProperties}, {rsCharacteristic.Value.Characteristic.Uuid}"; Debug.WriteLine(msg); await Task.Delay(TimeSpan.FromMilliseconds(100)); } }
IBuffer getBuffer(short i) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteInt16(i); return(writer.DetachBuffer()); }
public static async void SetSensorPeriod(SensorChars sensorCharacteristics, int period) { SensorServicesCls.SensorIndexes SensorIndex = sensorCharacteristics.Sensor_Index; Debug.WriteLine("Begin SetSensorPeriod(): " + SensorIndex.ToString()); try { if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Period)) { GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Period]; { if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); // Accelerometer period = [Input * 10]ms writer.WriteByte((Byte)(period / 10)); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } } catch (Exception ex) { Debug.WriteLine("Error: SetSensorPeriod(): " + SensorIndex.ToString() + " " + ex.Message); } Debug.WriteLine("End SetSensorPeriod(): " + SensorIndex.ToString()); }
private async void SendData(GattCharacteristic characteristic, string str) { var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.WriteString(str); await characteristic.WriteValueAsync(dataWriter.DetachBuffer()); }
protected override void OnNavigatedTo(NavigationEventArgs e) { if (this.Frame.CanGoBack) { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; SystemNavigationManager.GetForCurrentView().BackRequested += Publish_BackRequested; } this.publisher = new BluetoothLEAdvertisementPublisher(); ushort id = 0x1234; var manufacturerDataWriter = new DataWriter(); manufacturerDataWriter.WriteUInt16(id); var manufacturerData = new BluetoothLEManufacturerData { CompanyId = 0xFFFE, Data = manufacturerDataWriter.DetachBuffer() }; publisher.Advertisement.ManufacturerData.Add(manufacturerData); this.Manufacturer = "12-34"; publisher.Start(); }
private void PublishLaunchApp() { proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault(); if (proximityDevice != null) { // The format of the app launch string is: "<args>\tWindows\t<AppName>". // The string is tab or null delimited. // The <args> string must have at least one character. string launchArgs = "user=default"; // The format of the AppName is: PackageFamilyName!PRAID. string praid = "MyAppId"; // The Application Id value from your package.appxmanifest. string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid; string launchAppMessage = launchArgs + "\tWindows\t" + appName; var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE; dataWriter.WriteString(launchAppMessage); publishedUriId = proximityDevice.PublishBinaryMessage( "NDEF:WriteTag", dataWriter.DetachBuffer(), proximityWriteTagLaunchAppMessageTransmitCallback); } }
/// <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; }
// --------------------------------------------------- // Hardware Configuration Helper Functions // --------------------------------------------------- // Retrieve Barometer Calibration data private async void calibrateBarometer() { GattDeviceService gattService = serviceList[BAROMETRIC_PRESSURE]; if (gattService != null) { // Set Barometer configuration to 2, so that calibration data is saved var characteristicList = gattService.GetCharacteristics(new Guid("F000AA42-0451-4000-B000-000000000000")); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte((Byte)0x02); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } // Save Barometer calibration data characteristicList = gattService.GetCharacteristics(new Guid("F000AA43-0451-4000-B000-000000000000")); if (characteristicList != null) { GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached); baroCalibrationData = new byte[result.Value.Length]; DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData); } } }
public static void iBeaconSetAdvertisement(this BluetoothLEAdvertisement Advertisment, iBeaconData data) { BluetoothLEManufacturerData manufacturerData = new BluetoothLEManufacturerData(); // Set Apple as the manufacturer data manufacturerData.CompanyId = 76; var writer = new DataWriter(); writer.WriteUInt16(0x0215); //bytes 0 and 1 of the iBeacon advertisment indicator if (data!=null& data.UUID!= Guid.Empty) { //If UUID is null scanning for all iBeacons writer.WriteBytes( data.UUID.ToByteArray()); if (data.Major!=0) { //If Major not null searching with UUID and Major writer.WriteBytes(BitConverter.GetBytes(data.Major).Reverse().ToArray()); if (data.Minor != 0) { //If Minor not null we are looking for a specific beacon not a class of beacons writer.WriteBytes(BitConverter.GetBytes(data.Minor).Reverse().ToArray()); if (data.TxPower != 0) writer.WriteBytes(BitConverter.GetBytes(data.TxPower)); } } } manufacturerData.Data = writer.DetachBuffer(); Advertisment.ManufacturerData.Clear(); Advertisment.ManufacturerData.Add(manufacturerData); }
public async Task<bool> Init() { var res = true; ClearExceptions(); for (int i = 0; i < 20; i++) { try { var value = new byte[3]; value[0] = 0x1; value[1] = (byte)(i + 1); value[2] = (byte)(i + 1); var buffer = new DataWriter(); buffer.WriteBytes(value); await _initCount1To20Char.WriteValueAsync(buffer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); await Sleep(50); } catch (Exception exception) { res = false; AddException(exception); } } return res; }
// Write function for adding control points to a server private async Task HandleSensorControlPoint(string data) { if (!string.IsNullOrEmpty(data)) { // Get current service from base class. var service = await GetService(); // Get current characteristic from current service using the selected values from the base class. var characteristic = service.GetCharacteristics(this.SelectedService.Guid)[this.SelectedIndex]; //Create an instance of a data writer which will write to the relevent buffer. DataWriter writer = new DataWriter(); byte[] toWrite = System.Text.Encoding.UTF8.GetBytes(data); writer.WriteBytes(toWrite); // Attempt to write the data to the device, and whist doing so get the status. GattCommunicationStatus status = await characteristic.WriteValueAsync(writer.DetachBuffer()); // Displays a message box to tell user if the write operation was successful or not. if (status == GattCommunicationStatus.Success) { MessageHelper.DisplayBasicMessage("Sensor control point has been written."); } else { MessageHelper.DisplayBasicMessage("There was a problem writing the sensor control value, Please try again later."); } } }
// --------------------------------------------------- // Hardware Configuration Helper Functions // --------------------------------------------------- // Retrieve Barometer Calibration data private async void calibrateBarometer() { GattDeviceService service; if (_serviceList.TryGetValue(BAROMETRIC_PRESSURE, out service)) { // Set Barometer configuration to 2, so that calibration data is saved var characteristicList = service.GetCharacteristics(BAROMETER_CONFIGURATION_GUID); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteByte((Byte)0x02); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } // Save Barometer calibration data characteristicList = service.GetCharacteristics(BAROMETER_CALIBRATION_GUID); if (characteristicList != null) { GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached); baroCalibrationData = new byte[result.Value.Length]; DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData); } } }
/// <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(); // 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); }
public static IBuffer GetBufferFromByteArray(this byte[] payload) { using (var dw = new DataWriter()) { dw.WriteBytes(payload); return dw.DetachBuffer(); } }
public HidOutputReport GetFilledReport() { var dataWriter = new DataWriter(); dataWriter.WriteByte(Id); dataWriter.WriteBytes(Data.Array); report.Data = dataWriter.DetachBuffer(); return report; }
public async Task SetAcquisitionRateAsync(UInt16 rate) { var acqusitionCharacteristic = service.GetCharacteristics(new Guid("00000EE2-0000-1000-8000-00805f9b34fb"))[0]; DataWriter writer = new DataWriter(); //Endianess of reciever data inverted writer.WriteInt16((Int16) SwapUInt16(rate)); var status = await acqusitionCharacteristic.WriteValueAsync(writer.DetachBuffer()); }
private static byte[] GetDataIn(byte serviceCount, byte[] serviceCodeList, byte blockCount, byte[] blockList) { DataWriter dataWriter = new DataWriter(); dataWriter.WriteByte(serviceCount); dataWriter.WriteBytes(serviceCodeList); dataWriter.WriteByte(blockCount); dataWriter.WriteBytes(blockList); return dataWriter.DetachBuffer().ToArray(); }
private IBuffer GetBufferFromString(String str) { using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { using (DataWriter dataWriter = new DataWriter(memoryStream)) { dataWriter.WriteString(str); return dataWriter.DetachBuffer(); } } }
public static IBuffer getBufferFromString(String encodedText) { using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { using (DataWriter dataWriter = new DataWriter(memoryStream)) { byte[] decodedBytes = Convert.FromBase64String(encodedText); dataWriter.WriteBytes(decodedBytes); return dataWriter.DetachBuffer(); } } }
public static IBuffer ToIBuffer(byte[] value) { if(value == null && value.Length == 0) throw new ArgumentException(); var temp = new byte[value.Length]; Array.Copy(value, 0, temp, 0, value.Length); using (DataWriter writer = new DataWriter()) { writer.WriteBytes(temp); var buffer = writer.DetachBuffer(); return buffer; } }
void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(MINIMUM_SERVICE_VERSION); IBuffer data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data); }
public override async System.Threading.Tasks.Task<SensorBase.InitResult> Init() { var r = await base.Init(); if (r == InitResult.Ok) { // Lecture des données de calibration GattCommunicationStatus s; using (var writer = new DataWriter()) { writer.WriteByte(2); s = await pConfigurationCharacteristic.WriteValueAsync(writer.DetachBuffer()); } if (s == GattCommunicationStatus.Success) { var calib = GetCharacteristic(pDeviceService, BAROMETER_CALIBRATION_UUID); if (calib != null) { var result = await calib.ReadValueAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success && result.Value.Length == 16) { byte[] b = new byte[16]; DataReader wReader = DataReader.FromBuffer(result.Value); using (wReader) { wReader.ReadBytes(b); } pBarometerCalibrationData[0] = BitConverter.ToUInt16(b, 0); pBarometerCalibrationData[1] = BitConverter.ToUInt16(b, 2); pBarometerCalibrationData[2] = BitConverter.ToUInt16(b, 4); pBarometerCalibrationData[3] = BitConverter.ToUInt16(b, 6); pBarometerCalibrationData[4] = BitConverter.ToInt16(b, 8); pBarometerCalibrationData[5] = BitConverter.ToInt16(b, 10); pBarometerCalibrationData[6] = BitConverter.ToInt16(b, 12); pBarometerCalibrationData[7] = BitConverter.ToInt16(b, 14); } } } } return r; }
static async void MainAsync(string[] args) { var baseGuid = new Guid("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); var txGuid = new Guid("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); var rxGuid = new Guid("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); var selector = GattDeviceService.GetDeviceSelectorFromUuid(baseGuid); var services = await DeviceInformation.FindAllAsync(selector); var id = services[0].Id; var name = services[0].Name; Console.WriteLine("Using Service: {0}", name); var service = await GattDeviceService.FromIdAsync(id); var gattTx = service.GetCharacteristics(txGuid)[0]; var txProps = gattTx.CharacteristicProperties; var isWWR = txProps.HasFlag(GattCharacteristicProperties.WriteWithoutResponse); var isWR = txProps.HasFlag(GattCharacteristicProperties.Write); var isRR = txProps.HasFlag(GattCharacteristicProperties.ReliableWrites); var isSR = txProps.HasFlag(GattCharacteristicProperties.AuthenticatedSignedWrites); Console.WriteLine("Tx :" + gattTx.CharacteristicProperties); var gattRx = service.GetCharacteristics(rxGuid)[0]; var rxProps = gattRx.CharacteristicProperties; var isIR = rxProps.HasFlag(GattCharacteristicProperties.Read); var isRN = rxProps.HasFlag(GattCharacteristicProperties.Notify); var isRI = rxProps.HasFlag(GattCharacteristicProperties.Indicate); var isRB = rxProps.HasFlag(GattCharacteristicProperties.Broadcast); Console.WriteLine("Rx :" + gattRx.CharacteristicProperties); gattRx.ValueChanged += GattRx_ValueChanged; // var val = await gattRx.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Cached); Console.WriteLine("Callback enabled. Type stuff to send"); string data = string.Empty; while (data.ToUpper() != "Q") { data = Console.ReadLine(); var writer = new DataWriter(); writer.WriteString(data); var res = await gattTx.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithResponse); Console.Write(data); Console.WriteLine(res); } }
public async void OnCommandRecived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; string command = message["Command"] as string; if (command.Equals("BluetoothBridge")) { var value = message["Value"] as string; var device = message["Device"] as string; var writer = new DataWriter(); writer.WriteString(value); await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer()); } }
private async void btnColor_Click(object sender, RoutedEventArgs e) { //Change the color of the NeoPixel by writing the hex color bytes to the Write characteristic //that is currently being monitored by our Flora sketch Button btnColor = (Button)sender; var color = ((SolidColorBrush)btnColor.Background).Color; var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(new byte[] { color.R, color.G, color.B }); txtProgress.Text = "Writing color to Writable GATT characteristic ..."; await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer()); txtProgress.Text = "Writable GATT characteristic written"; }
public IAsyncOperationWithProgress<IBuffer, ulong> ReadAsBufferAsync() { return AsyncInfo.Run<IBuffer, ulong>((cancellationToken, progress) => { return Task<IBuffer>.Run(() => { DataWriter writer = new DataWriter(); writer.WriteString(jsonValue.Stringify()); // Make sure that the DataWriter destructor does not free the buffer. IBuffer buffer = writer.DetachBuffer(); // Report progress. progress.Report(buffer.Length); return buffer; }); }); }
public async Task<bool> Takeoff() { var result = true; ClearExceptions(); try { byte[] arr = { 4, (byte)_settingsCounter, 2, 0, 1, 0 }; var buffer = new DataWriter(); buffer.WriteBytes(arr); await _datetimeChar.WriteValueAsync(buffer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); } catch (Exception exception) { AddException(exception); result = false; } await Sleep(50); _settingsCounter++; return result; }
/// <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 Scenario2_Publisher() { this.InitializeComponent(); // Create and initialize a new publisher instance. publisher = new BluetoothLEAdvertisementPublisher(); // We need to add some payload to the advertisement. A publisher without any payload // or with invalid ones cannot be started. We only need to configure the payload once // for any publisher. // Add a manufacturer-specific section: // First, let create a manufacturer data section var manufacturerData = new BluetoothLEManufacturerData(); // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0x004C; // 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(); //UInt16 uuidData = 0x1234; //writer.WriteUInt16(uuidData); writer.WriteBytes(BleData.ReceivedData); // 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 publisher: publisher.Advertisement.ManufacturerData.Add(manufacturerData); // Display the information about the published payload PublisherPayloadBlock.Text = string.Format("Published payload information: CompanyId=0x{0}, ManufacturerData=0x{1}", manufacturerData.CompanyId.ToString("X"), BitConverter.ToString(BleData.ReceivedData)); // Display the current status of the publisher PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}", publisher.Status, BluetoothError.Success); }
// Set sensor update period private async void setSensorPeriod(int sensor, int period) { GattDeviceService gattService = serviceList[sensor]; if (sensor != KEYS && gattService != null) { var characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_PERIOD_GUID_SUFFFIX)); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); // Accelerometer period = [Input * 10]ms writer.WriteByte((Byte)(period / 10)); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } }
public async void setSensorPeriod(int period) { GattDeviceService gattService = GattService; if (SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && gattService != null) { var characteristicList = gattService.GetCharacteristics(new Guid(UUIDBase[(int)SensorIndex] + SENSOR_PERIOD_GUID_SUFFFIX)); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); // Accelerometer period = [Input * 10]ms writer.WriteByte((Byte)(period / 10)); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } }
void InitializeServiceSdpAttributes(RfcommServiceProvider provider) { try { var writer = new Windows.Storage.Streams.DataWriter(); // First write the attribute type writer.WriteByte(Constants.SERVICE_VERSION_ATTRIBUTE_TYPE); // Then write the data writer.WriteUInt32(Constants.SERVICE_VERSION); var data = writer.DetachBuffer(); provider.SdpRawAttributes.Add(Constants.SERVICE_VERSION_ATTRIBUTE_ID, data); //Check attributes try { var attributes = provider.SdpRawAttributes; // BluetoothCacheMode.Uncached); var attribute = attributes[Constants.SERVICE_VERSION_ATTRIBUTE_ID]; var reader = DataReader.FromBuffer(attribute); // The first byte contains the attribute' s type byte attributeType = reader.ReadByte(); if (attributeType == Constants.SERVICE_VERSION_ATTRIBUTE_TYPE) { // The remainder is the data uint version = reader.ReadUInt32(); bool ret = (version >= Constants.MINIMUM_SERVICE_VERSION); } } catch (Exception ex) { PostMessage("OBEX_Recv.InitializeServiceSdpAttributes_Check", ex.Message); } } catch (Exception ex) { PostMessage("OBEX_Receiver.InitializeServiceSdpAttributes", ex.Message); } }
/// <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 Scenario4_BackgroundPublisher() { this.InitializeComponent(); // Create and initialize a new trigger to configure it. trigger = new BluetoothLEAdvertisementPublisherTrigger(); // We need to add some payload to the advertisement. A publisher without any payload // or with invalid ones cannot be started. We only need to configure the payload once // for any publisher. // Add a manufacturer-specific section: // First, create a manufacturer data section 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(); UInt16 uuidData = 0x1234; writer.WriteUInt16(uuidData); // 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 publisher: trigger.Advertisement.ManufacturerData.Add(manufacturerData); // Display the information about the published payload PublisherPayloadBlock.Text = string.Format("Published payload information: CompanyId=0x{0}, ManufacturerData=0x{1}", manufacturerData.CompanyId.ToString("X"), uuidData.ToString("X")); // Reset the displayed status of the publisher PublisherStatusBlock.Text = ""; }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { var bts = await DeviceInformation.FindAllAsync(); const string deviceId = @"\\?\BTHLEDevice#{9a66fa00-0800-9191-11e4-012d1540cb8e}_e0144d4f3d49#a&1f09a1af&0&0020#{6e3bb679-4372-40c8-9eaa-4509df260cd8}"; var device = bts.First(di => di.Name == DeviceName && di.Id == deviceId); if (null == device) return; _service = await GattDeviceService.FromIdAsync(device.Id); if (null == _service) return; _characteristics = _service.GetAllCharacteristics(); if (null == _characteristics || _characteristics.Count <= 0) return; var characteristic = _characteristics.First(charact => charact.Uuid == RollingSpiderCharacteristicUuids.Parrot_PowerMotors); try { var charName = CharacteristicUuidsResolver.GetNameFromUuid(characteristic.Uuid); Debug.WriteLine(charName); for (int i = 0; i < 255; i++) { Debug.WriteLine(i); byte[] arr = { (byte)02, (byte)40, (byte)20, (byte)0D, 00, 09, 00, 04, 00, 52, 43, 00, 04, (byte)i, 02, 00, 01, 00, }; var writer = new DataWriter(); writer.WriteBytes(arr); await characteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); await Task.Delay(TimeSpan.FromSeconds(1)); } } catch { } }
// Enable and subscribe to specified GATT characteristic private async Task enableSensor(int sensor) { Debug.WriteLine("Begin enable sensor: " + sensor.ToString()); GattDeviceService gattService = serviceList[sensor]; if (gattService != null) { // Turn on notifications IReadOnlyList <GattCharacteristic> characteristicList; if (sensor >= 0 && sensor <= 5) { characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX)); } else { characteristicList = gattService.GetCharacteristics(BUTTONS_NOTIFICATION_GUID); } if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { switch (sensor) { case (IR_SENSOR): characteristic.ValueChanged += tempChanged; IRTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (ACCELEROMETER): characteristic.ValueChanged += accelChanged; AccelTitle.Foreground = new SolidColorBrush(Colors.Green); setSensorPeriod(ACCELEROMETER, 250); break; case (HUMIDITY): characteristic.ValueChanged += humidChanged; HumidTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (MAGNETOMETER): characteristic.ValueChanged += magnoChanged; MagnoTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (BAROMETRIC_PRESSURE): characteristic.ValueChanged += pressureChanged; BaroTitle.Foreground = new SolidColorBrush(Colors.Green); calibrateBarometer(); break; case (GYROSCOPE): characteristic.ValueChanged += gyroChanged; GyroTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (KEYS): characteristic.ValueChanged += keyChanged; KeyTitle.Foreground = new SolidColorBrush(Colors.Green); break; default: break; } // Save a reference to each active characteristic, so that handlers do not get prematurely killed activeCharacteristics[sensor] = characteristic; // Set the notify enable flag await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } // Turn on sensor if (sensor >= 0 && sensor <= 5) { characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX)); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.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 { writer.WriteByte((Byte)0x01); } await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } } Debug.WriteLine("End enable sensor: " + sensor.ToString()); }
public static async Task TurnOffSensor(SensorChars sensorCharacteristics) { SensorServicesCls.SensorIndexes SensorIndex = sensorCharacteristics.Sensor_Index; Debug.WriteLine("Begin turn off sensor: " + SensorIndex.ToString()); try { // Turn on sensor if (SensorIndex >= 0 && SensorIndex != SensorServicesCls.SensorIndexes.KEYS && SensorIndex != SensorServicesCls.SensorIndexes.IO_SENSOR && SensorIndex != SensorServicesCls.SensorIndexes.REGISTERS) { if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Enable)) { GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Enable]; if (characteristic != null) { if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); if (SensorIndex == SensorServicesCls.SensorIndexes.MOVEMENT) { byte[] bytes = new byte[] { 0x00, 0x00 };//Fixed writer.WriteBytes(bytes); } else { writer.WriteByte((Byte)0x00); } var status = await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } } } catch (Exception ex) { Debug.WriteLine("Error: TurnOffSensor(): " + SensorIndex.ToString() + " " + ex.Message); } Debug.WriteLine("End turn off sensor: " + SensorIndex.ToString()); }
private async void ButtonAction3_Click(object sender, RoutedEventArgs e) { var writeableChars = new[] {"Parrot_FC1", "Parrot_D22", "Parrot_D23", "Parrot_D24", "Parrot_D52", "Parrot_D53", "Parrot_D54"}; DevicesInformation = string.Empty; foreach (var writeableChar in writeableChars) { foreach (var rsCharacteristic in _dicCharacteristics.Where(rsCharacteristic => rsCharacteristic.Value.CharName == writeableChar)) { await rsCharacteristic.Value.Characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); DevicesInformation += $" Test write {rsCharacteristic.Value.CharName}{Environment.NewLine}"; try { var charToTest = rsCharacteristic.Value.Characteristic; byte[] arr1 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xC0, 00, 01, 00 }; var writer = new DataWriter(); writer.WriteBytes(arr1); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 1 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); byte[] arr2 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xBD, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr2); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 2 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); byte[] arr3 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xE4, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr3); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 3 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); byte[] arr4 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xE7, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr4); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 4 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); byte[] arr5 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 52, 16, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr5); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 5 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); byte[] arr6 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 52, 26, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr6); await charToTest.WriteValueAsync(writer.DetachBuffer()); DevicesInformation += $" - 6 OK{Environment.NewLine}"; await Task.Delay(TimeSpan.FromMilliseconds(100)); } catch { DevicesInformation += $" - ERROR{Environment.NewLine}"; } } } DevicesInformation += "Done"; }
private async Task enableSensor(int sensor) { Debug.WriteLine("Begin enable sensor: " + sensor.ToString()); GattDeviceService gattService = serviceList[sensor]; if (gattService != null) { // Turn on notifications IReadOnlyList <GattCharacteristic> characteristicList; if (sensor >= 0 && sensor <= 2) { characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX)); } else { characteristicList = gattService.GetCharacteristics(LUXOMETER_CONFIGURATION_GUID); } if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { switch (sensor) { case (IR_SENSOR): characteristic.ValueChanged += tempChanged; break; case (HUMIDITY): characteristic.ValueChanged += humidChanged; break; case (LUXOMETER): characteristic.ValueChanged += luxChanged; //BaroTitle.Foreground = new SolidColorBrush(Colors.Green); break; default: break; } // Save a reference to each active characteristic, so that handlers do not get prematurely killed activeCharacteristics[sensor] = characteristic; // Set the notify enable flag await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } // Turn on sensor if (sensor >= 0 && sensor <= 7) { characteristicList = gattService.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX)); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write)) { var writer = new Windows.Storage.Streams.DataWriter(); // Special value for Gyroscope to enable all 3 axes writer.WriteByte((Byte)0x01); await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } } Debug.WriteLine("End enable sensor: " + sensor.ToString()); }
private async void ButtonAction5_Click(object sender, RoutedEventArgs e) { DevicesInformation = string.Empty; try { var motors = _dicCharacteristics["Parrot_PowerMotors"].Characteristic; await motors.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate); byte[] arr1 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xC0, 00, 01, 00 }; var buffer = new DataWriter(); buffer.WriteInt16(2); buffer.WriteInt16(1); buffer.WriteInt16(2); buffer.WriteInt16(0); buffer.WriteInt16(2); buffer.WriteInt16(0); buffer.WriteInt16(1); buffer.WriteInt16(1); buffer.WriteInt16(1); buffer.WriteInt16(1); buffer.WriteInt16(1); buffer.WriteDouble(0); await motors.WriteValueAsync(buffer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); DevicesInformation += $" - 1 OK{Environment.NewLine}"; } catch (Exception exception) { DevicesInformation += $" - ERROR {exception.Message}{Environment.NewLine}"; } }
private async Task <bool> WriteSensor(byte[] bytes, ServiceCharacteristicsEnum characteristicEnum) { bool ret = false; Debug.WriteLine("Begin WriteSensor: " + SensorIndex.ToString()); try { if (GattService != null) { GattCharacteristic characteristic = null; GattCharacteristicProperties flag = GattCharacteristicProperties.Write; switch (characteristicEnum) { case ServiceCharacteristicsEnum.Data: characteristic = this.Data; break; case ServiceCharacteristicsEnum.Notification: flag = GattCharacteristicProperties.Notify; characteristic = this.Notification; break; case ServiceCharacteristicsEnum.Configuration: characteristic = this.Configuration; break; case ServiceCharacteristicsEnum.Period: characteristic = this.GattCharacteristicPeriod; break; case ServiceCharacteristicsEnum.Address: characteristic = this.Address; break; case ServiceCharacteristicsEnum.Device_Id: characteristic = this.Device_Id; break; } if (characteristic != null) { if (characteristic.CharacteristicProperties.HasFlag(flag)) { var writer = new Windows.Storage.Streams.DataWriter(); writer.WriteBytes(bytes); var status = await characteristic.WriteValueAsync(writer.DetachBuffer()); if (status == GattCommunicationStatus.Success) { ret = true; } } } } } catch (Exception ex) { Debug.WriteLine("Error: WriteSensor(): " + SensorIndex.ToString() + " " + ex.Message); } Debug.WriteLine("End WriteSensor " + SensorIndex.ToString()); return(ret); }
private async void WriteBlock_Click(object sender, RoutedEventArgs e) { var fx2Device = DeviceList.Current.GetSelectedDevice(); if (fx2Device == null) { rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage); return; } var button = (Button)sender; button.IsEnabled = false; // Generate a string to write to the device var counter = writeCounter++; // Use a data writer to convert the string into a buffer var dataWriter = new DataWriter(); var msg = "This is message " + counter; dataWriter.WriteString(msg); LogMessage("Write {0} begin: {1}", counter, msg); var bytesRead = await fx2Device.OutputStream.WriteAsync(dataWriter.DetachBuffer()); LogMessage("Write {0} end: {1} bytes written", counter, bytesRead); button.IsEnabled = true; }
// Enable and subscribe to specified GATT characteristic private async Task enableSensor(int sensor) { GattDeviceService sensorDevice; if (_serviceList.TryGetValue(sensor, out sensorDevice)) { GattCharacteristic notification; lock (_notifyList) { if (!_notifyList.TryGetValue(sensor, out notification)) { IReadOnlyList <GattCharacteristic> notificationList; if (sensor >= 0 && sensor <= 5) { notificationList = sensorDevice.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_NOTIFICATION_GUID_SUFFFIX)); } else { notificationList = sensorDevice.GetCharacteristics(BUTTONS_NOTIFICATION_GUID); } if (notificationList != null) { _notifyList.Add(sensor, notificationList[0]); } } } if (_notifyList.TryGetValue(sensor, out notification)) { Debug.WriteLine($"Begin enable sensor {sensor} - {notification.UserDescription}"); if (notification.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { switch (sensor) { case (IR_SENSOR): notification.ValueChanged += tempChanged; break; case (ACCELEROMETER): notification.ValueChanged += accelChanged; setSensorPeriod(ACCELEROMETER, 250); break; case (HUMIDITY): notification.ValueChanged += humidChanged; break; case (MAGNETOMETER): notification.ValueChanged += magnoChanged; break; case (BAROMETRIC_PRESSURE): notification.ValueChanged += pressureChanged; calibrateBarometer(); break; case (GYROSCOPE): notification.ValueChanged += gyroChanged; break; case (KEYS): notification.ValueChanged += keyChanged; break; default: break; } // Set the notify enable flag var unused = await notification.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } // Turn on sensor if (sensor >= 0 && sensor <= 5) { IReadOnlyList <GattCharacteristic> enableCharacteristicList = sensorDevice.GetCharacteristics(new Guid(SENSOR_GUID_PREFIX + sensor + SENSOR_ENABLE_GUID_SUFFFIX)); if (enableCharacteristicList != null) { GattCharacteristic characteristic = enableCharacteristicList[0]; if (characteristic.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 { writer.WriteByte((Byte)0x01); } await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } // update UI and set value changed await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { switch (sensor) { case (IR_SENSOR): IRTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (ACCELEROMETER): AccelTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (HUMIDITY): HumidTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (MAGNETOMETER): MagnoTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (BAROMETRIC_PRESSURE): BaroTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (GYROSCOPE): GyroTitle.Foreground = new SolidColorBrush(Colors.Green); break; case (KEYS): KeyTitle.Foreground = new SolidColorBrush(Colors.Green); break; default: break; } }); } }
// Handles PeerFinder_AdvertiseButton click void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e) { // If PeerFinder is started, stop it, so that new properties // selected by the user (Role/DiscoveryData) can be updated. if (_peerFinderStarted) { PeerFinder.Stop(); _peerFinderStarted = false; } rootPage.NotifyUser("", NotifyType.ErrorMessage); if (!_peerFinderStarted) { // attach the callback handler (there can only be one PeerConnectProgress handler). PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler); // attach the incoming connection request event handler PeerFinder.ConnectionRequested += new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested); // Set the PeerFinder.Role property if (_launchByTap) { PeerFinder.Role = rootPage.GetLaunchRole(); } else { switch (PeerFinder_SelectRole.SelectionBoxItem.ToString()) { case "Peer": PeerFinder.Role = PeerRole.Peer; break; case "Host": PeerFinder.Role = PeerRole.Host; break; case "Client": PeerFinder.Role = PeerRole.Client; break; } } // Set DiscoveryData property if the user entered some text if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?")) { using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream())) { discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text); PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer(); } } // start listening for proximate peers PeerFinder.Start(); _peerFinderStarted = true; if (_browseConnectSupported && _triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer or click Browse for Peers button.", NotifyType.StatusMessage); PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible; PeerFinder_SelectRole.Visibility = Visibility.Visible; PeerFinder_DiscoveryData.Visibility = Visibility.Visible; } else if (_triggeredConnectSupported) { rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage); PeerFinder_SelectRole.Visibility = Visibility.Visible; } else if (_browseConnectSupported) { rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage); PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible; PeerFinder_SelectRole.Visibility = Visibility.Visible; PeerFinder_DiscoveryData.Visibility = Visibility.Visible; } } }
public static async void Interact(anki_vehicle vehicle, GattCharacteristic readChar, GattCharacteristic writeChar) { try { var writer = new Windows.Storage.Streams.DataWriter(); byte[] rawBytes = null; GattCommunicationStatus result; readChar.ValueChanged += VehicleResponse; if (readChar.CharacteristicProperties == (GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify)) { result = await readChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } while (true) { Console.Write("Please enter your command: "); string input = Console.ReadLine(); if (input == "exit") { return; } switch (input) { case "ping": { anki_vehicle_msg msg = new anki_vehicle_msg(); msg.size = ANKI_VEHICLE_MSG_BASE_SIZE; msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_PING_REQUEST; rawBytes = getBytes(msg); writer.WriteBytes(rawBytes); result = await writeChar.WriteValueAsync(writer.DetachBuffer()); break; } case "get-version": { anki_vehicle_msg msg = new anki_vehicle_msg(); msg.size = ANKI_VEHICLE_MSG_BASE_SIZE; msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST; rawBytes = getBytes(msg); writer.WriteBytes(rawBytes); result = await writeChar.WriteValueAsync(writer.DetachBuffer()); break; } case "get-battery": { anki_vehicle_msg msg = new anki_vehicle_msg(); msg.size = ANKI_VEHICLE_MSG_BASE_SIZE; msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST; rawBytes = getBytes(msg); writer.WriteBytes(rawBytes); result = await writeChar.WriteValueAsync(writer.DetachBuffer()); break; } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
// Enable and subscribe to specified GATT characteristic private async void enableSensor(int sensor) { GattDeviceService gattService = serviceList[sensor]; if (gattService != null) { // Turn on notifications IReadOnlyList <GattCharacteristic> characteristicList; if (sensor >= 0 && sensor <= 5) { characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "1-0451-4000-B000-000000000000")); } else { characteristicList = gattService.GetCharacteristics(new Guid("0000FFE1-0000-1000-8000-00805F9B34FB")); } if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { switch (sensor) { /* * case (IR_SENSOR): * characteristic.ValueChanged += tempChanged; * IRTitle.Foreground = new SolidColorBrush(Colors.Green); * break; * case (ACCELEROMETER): * characteristic.ValueChanged += accelChanged; * AccelTitle.Foreground = new SolidColorBrush(Colors.Green); * setSensorPeriod(ACCELEROMETER, 250); * break; * case (HUMIDITY): * characteristic.ValueChanged += humidChanged; * HumidTitle.Foreground = new SolidColorBrush(Colors.Green); * break; * case (MAGNETOMETER): * characteristic.ValueChanged += magnoChanged; * MagnoTitle.Foreground = new SolidColorBrush(Colors.Green); * break; * case (BAROMETRIC_PRESSURE): * characteristic.ValueChanged += pressureChanged; * BaroTitle.Foreground = new SolidColorBrush(Colors.Green); * calibrateBarometer(); * break; * case (GYROSCOPE): * characteristic.ValueChanged += gyroChanged; * GyroTitle.Foreground = new SolidColorBrush(Colors.Green); * break; */ case (KEYS): characteristic.ValueChanged += keyChanged; // KeyTitle.Foreground = new SolidColorBrush(Colors.Green); break; default: break; } // Save a reference to each active characteristic, so that handlers do not get prematurely killed activeCharacteristics[sensor] = characteristic; // Set the notify enable flag await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); } } // Turn on sensor if (sensor >= 0 && sensor <= 5) { characteristicList = gattService.GetCharacteristics(new Guid("F000AA" + sensor + "2-0451-4000-B000-000000000000")); if (characteristicList != null) { GattCharacteristic characteristic = characteristicList[0]; if (characteristic.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 { writer.WriteByte((Byte)0x01); } await characteristic.WriteValueAsync(writer.DetachBuffer()); } } } } }
private async Task <bool> SendPowerOffCommand() { var writer = new Windows.Storage.Streams.DataWriter(); short val = CMD_OFF; writer.WriteInt16(val); GattCommunicationStatus writeResult = await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer()); bool success = writeResult == GattCommunicationStatus.Success; return(success); }
public void StartAdvertisement( string serviceName, bool autoAccept, bool preferGO, string pin, IList <WiFiDirectServiceConfigurationMethod> configMethods, WiFiDirectServiceStatus status, uint customStatus, string serviceInfo, string deferredServiceInfo, IList <String> prefixList ) { ThrowIfDisposed(); // Create Advertiser object for the service // NOTE: service name is internally limited to up to 255 bytes in UTF-8 encoding // Valid characters include alpha-numeric, '.', '-', and any multi-byte character // characters a-z, A-Z are case-insensitive when discovering services WiFiDirectServiceAdvertiser advertiser = new WiFiDirectServiceAdvertiser(serviceName); // Auto-accept services will connect without interaction from advertiser // NOTE: if the config method used for a connection requires a PIN, then the advertiser will have to accept the connection advertiser.AutoAcceptSession = autoAccept; // Set the Group Owner intent to a large value so that the advertiser will try to become the group owner (GO) // NOTE: The GO of a P2P connection can connect to multiple clients while the client can connect to a single GO only advertiser.PreferGroupOwnerMode = preferGO; // Default status is "Available", but services may use a custom status code (value > 1) if applicable advertiser.ServiceStatus = status; advertiser.CustomServiceStatusCode = customStatus; // Service information can be up to 65000 bytes. // Service Seeker may explicitly discover this by specifying a short buffer that is a subset of this buffer. // If seeker portion matches, then entire buffer is returned, otherwise, the service information is not returned to the seeker // This sample uses a string for the buffer but it can be any data if (serviceInfo != null && serviceInfo.Length > 0) { using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream)) { serviceInfoDataWriter.WriteString(serviceInfo); advertiser.ServiceInfo = serviceInfoDataWriter.DetachBuffer(); } } } else { advertiser.ServiceInfo = null; } // This is a buffer of up to 144 bytes that is sent to the seeker in case the connection is "deferred" (i.e. not auto-accepted) // This buffer will be sent when auto-accept is false, or if a PIN is required to complete the connection // For the sample, we use a string, but it can contain any data if (deferredServiceInfo != null && deferredServiceInfo.Length > 0) { using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { using (var deferredSessionInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream)) { deferredSessionInfoDataWriter.WriteString(deferredServiceInfo); advertiser.DeferredSessionInfo = deferredSessionInfoDataWriter.DetachBuffer(); } } } else { advertiser.DeferredSessionInfo = null; } // The advertiser supported configuration methods // Valid values are PIN-only (either keypad entry, display, or both), or PIN (keypad entry, display, or both) and WFD Services default // WFD Services Default config method does not require explicit PIN entry and offers a more seamless connection experience // Typically, an advertiser will support PIN display (and WFD Services Default), and a seeker will connect with either PIN entry or WFD Services Default if (configMethods != null) { advertiser.PreferredConfigurationMethods.Clear(); foreach (var configMethod in configMethods) { advertiser.PreferredConfigurationMethods.Add(configMethod); } } // Advertiser may also be discoverable by a prefix of the service name. Must explicitly specify prefixes allowed here. if (prefixList != null && prefixList.Count > 0) { advertiser.ServiceNamePrefixes.Clear(); foreach (var prefix in prefixList) { advertiser.ServiceNamePrefixes.Add(prefix); } } // For this sample, we wrap the advertiser in our own object which handles the advertiser events AdvertisementWrapper advertiserWrapper = new AdvertisementWrapper(advertiser, this, pin); AddAdvertiser(advertiserWrapper); RootPage.NotifyUser("Starting service...", NotifyType.StatusMessage); try { // This may fail if the driver is unable to handle the request or if services is not supported // NOTE: this must be called from the UI thread of the app advertiser.Start(); } catch (Exception ex) { RootPage.NotifyUser(String.Format(CultureInfo.InvariantCulture, "Failed to start service: {0}", ex.Message), NotifyType.ErrorMessage); throw; } }
private async void ButtonAction4_Click(object sender, RoutedEventArgs e) { var writeableChars = new[] {"Parrot_FC1", "Parrot_D22", "Parrot_D23", "Parrot_D24", "Parrot_D52", "Parrot_D53", "Parrot_D54"}; DevicesInformation = string.Empty; foreach (var writeableChar in writeableChars) { foreach (var rsCharacteristic in _dicCharacteristics.Where(rsCharacteristic => rsCharacteristic.Value.CharName == writeableChar)) { await rsCharacteristic.Value.Characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); DevicesInformation += $" Test write {rsCharacteristic.Value.CharName}{Environment.NewLine}"; try { var gattTransaction = new GattReliableWriteTransaction(); var charToTest = rsCharacteristic.Value.Characteristic; byte[] arr1 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xC0, 00, 01, 00 }; var writer = new DataWriter(); writer.WriteBytes(arr1); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 1 OK{Environment.NewLine}"; byte[] arr2 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xBD, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr2); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 2 OK{Environment.NewLine}"; byte[] arr3 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xE4, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr3); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 3 OK{Environment.NewLine}"; byte[] arr4 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 0xE7, 00, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr4); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 4 OK{Environment.NewLine}"; byte[] arr5 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 52, 16, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr5); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 5 OK{Environment.NewLine}"; byte[] arr6 = { 02, 40, 20, 09, 00, 05, 00, 04, 00, 12, 52, 26, 01, 00 }; writer = new DataWriter(); writer.WriteBytes(arr6); gattTransaction.WriteValue(charToTest, writer.DetachBuffer()); DevicesInformation += $" - 6 OK{Environment.NewLine}"; var status = await gattTransaction.CommitAsync(); switch (status) { case GattCommunicationStatus.Success: DevicesInformation += " Writing to your device OK !"; break; case GattCommunicationStatus.Unreachable: DevicesInformation += " Writing to your device Failed !"; break; } } catch (Exception exception) { DevicesInformation += $" - ERROR {exception.Message}{Environment.NewLine}"; } } } DevicesInformation += "Done"; }
/// <summary> /// Initialize the Rfcomm service's SDP attributes. /// </summary> /// <param name="rfcommProvider">The Rfcomm service provider to initialize.</param> private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider) { var sdpWriter = new DataWriter(); // Write the Service Name Attribute. sdpWriter.WriteByte(SdpServiceNameAttributeType); // The length of the UTF-8 encoded Service Name SDP Attribute. sdpWriter.WriteByte((byte)SdpServiceName.Length); // The UTF-8 encoded Service Name value. sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; sdpWriter.WriteString(SdpServiceName); // Set the SDP Attribute on the RFCOMM Service Provider. rfcommProvider.SdpRawAttributes.Add(SdpServiceNameAttributeId, sdpWriter.DetachBuffer()); }
internal async Task <bool> SendBLEData(StringBuilder sbCmd) { try { if (currentCharacteristic != null) { using (var writer = new Windows.Storage.Streams.DataWriter()) { writer.WriteString(sbCmd.ToString()); GattCommunicationStatus status = await currentCharacteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse); return(status == GattCommunicationStatus.Success); } } } catch (Exception e) { Debug.WriteLine(e); } return(false); }