To list the RFCOMM Bluetooth devices connected to the device, follow these steps:
var DEVICE_ID = new Guid("{00000000-0000-0000-0000-000000000000}"); //Enter your device RFCOMM service id (try to find it on manufactorer website var services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.FromUuid(DEVICE_ID)));
To connect to the first available device, follow these steps:
if (services.Count > 0) { var service = await RfcommDeviceService.FromIdAsync(services[0].Id);
To send data to the device and read the data back, follow these steps:
var BYTE_NUM = 64 as UInt32; //Read this many bytes IInputStream input = socket.InputStream; IOutputStream output = socket.OutputStream; var inputBuffer = new Buffer(); var operation = input.ReadAsync(inputBuffer, BYTE_NUM, InputStreamOptions.none); while (!operation.Completed) Thread.Sleep(200); inputBuffer = operation.GetResults(); var resultReader = DataReader.FromBuffer(inputBuffer); byte[] result = new byte[BYTE_NUM]; resultReader.ReadBytes(result); resultReader.Dispose(); //Do something with the bytes retrieved. If the Bluetooth device has an api, it will likely specify what bytes will be sent from the device //Now time to give some data to the device byte[] outputData = Encoding.ASCII.GetBytes("Hello, Bluetooth Device. Here some data! LALALALALA"); IBuffer outputBuffer = outputData.AsBuffer(); //Neat method, remember to include System.Runtime.InteropServices.WindowsRuntime operation = output.WriteAsync(outputBuffer); while (!operation.Completed) Thread.Sleep(200); await output.FlushAsync(); //Now the data has really been written
This will work on all RFCOMM (regular) Bluetooth devices, if your device uses Bluetooth Low Energy, please use the appropriate GATT classes.
Cheese lover
source share