Skip to content

Instantly share code, notes, and snippets.

@minakhan01
Created June 4, 2017 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minakhan01/aff6b136ff7d79ed1681a51e2d0b678e to your computer and use it in GitHub Desktop.
Save minakhan01/aff6b136ff7d79ed1681a51e2d0b678e to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Threading.Tasks;
using Windows.Storage.Streams;
#if NETFX_CORE
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Bluetooth.Advertisement;
#endif
public class Watcher : MonoBehaviour
{
#if NETFX_CORE
BluetoothLEAdvertisementWatcher watcher;
public static ushort BEACON_ID = 1775;
bool connected = false;
BluetoothLEDevice bleDevice;
string MyoServiceuuid = "D5060001-A904-DEB9-4748-2C7F4A124842";
string classifierServiceString = "D5060003-A904-DEB9-4748-2C7F4A124842";
static string firstPart = "d506";
static string lastPart = "-a904-deb9-4748-2c7f4a124842";
string commandCharacteristic = firstPart + "0401" + lastPart;
string ImuDataService = firstPart + "0002" + lastPart;
string IMUDataCharacteristic = firstPart + "0402" + lastPart;
string MotionEventCharacteristic = firstPart + "0502" + lastPart;
string ClassifierService = firstPart + "0003" + lastPart;
string ClassifierEventCharacteristic = firstPart + "0103" + lastPart;
string EmgDataService = firstPart + "0005" + lastPart;
string EmgData0Characteristic = firstPart + "0105" + lastPart;
string EmgData1Characteristic = firstPart + "0205" + lastPart;
string EmgData2Characteristic = firstPart + "0305" + lastPart;
string EmgData3Characteristic = firstPart + "0405" + lastPart;
#endif
void Awake()
{
#if NETFX_CORE
watcher = new BluetoothLEAdvertisementWatcher();
var manufacturerData = new BluetoothLEManufacturerData
{
CompanyId = BEACON_ID
};
//watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);
watcher.Received += Watcher_Received;
watcher.Start();
#endif
}
#if NETFX_CORE
private async void Watcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
if (args != null && args.Advertisement != null)
{
Debug.Log("device found");
if (args.Advertisement.ManufacturerData != null)
{
Debug.Log("manufacture data != null");
var manufacturerData = args.Advertisement.ManufacturerData;
Debug.Log("manufacture data isn't corrupted");
if (manufacturerData.Count > 0)
{
ushort identifier = args.Advertisement.ManufacturerData[0].CompanyId;
// string uuid = args.Advertisement.ServiceUuids[0].ToString();
// byte[] data = args.Advertisement.ManufacturerData[0].Data.ToArray();
Debug.Log("received: " );
}
}
Debug.Log("manufacture data found");
}
var uuid = args.Advertisement.ServiceUuids;
if (uuid.Count > 0)
{
string uuidString = uuid[0].ToString();
Debug.Log("uuid: " + uuidString);
if (uuidString.Equals(MyoServiceuuid) ||
uuidString.Equals(MyoServiceuuid.ToLower()))
{
Debug.Log("Myo found!");
ulong bluetoothAddress = args.BluetoothAddress;
//args.
try
{
bleDevice =
await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
watcher.Stop();
if (bleDevice != null)
{
DevicePairingResult result = await bleDevice.DeviceInformation.Pairing.PairAsync();
bleDevice.ConnectionStatusChanged += BleDevice_ConnectionStatusChanged;
//GattDeviceServicesResult gattServices = await bleDevice.GetGattServicesForUuidAsync(Guid.Parse(classifierServiceString));
//bool connected = false;
//int tryCount = 0;
//while (!connected)
//{
// tryCount++;
// GattDeviceServicesResult gattServices = await bleDevice.GetGattServicesAsync();
//}
}
}
catch (Exception ex)
{
Debug.Log("Not able to get");
Debug.Log(ex);
}
}
}
}
void Characteristic_ValueChanged(GattCharacteristic sender,
GattValueChangedEventArgs args)
{
// An Indicate or Notify reported that the value has changed.
var reader = DataReader.FromBuffer(args.CharacteristicValue);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
Debug.Log("sender id: "+sender.Uuid);
Debug.Log("Characteristic_ValueChanged");
Debug.Log("input: " + input[0]);
// Parse the data however required.
}
void Characteristic_IndicateChanged(GattCharacteristic sender,
GattValueChangedEventArgs args)
{
// An Indicate or Notify reported that the value has changed.
var reader = DataReader.FromBuffer(args.CharacteristicValue);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
Debug.Log("sender id: " + sender.Uuid);
Debug.Log("Characteristic_IndicateChanged");
Debug.Log("input: " + input[0]);
// Parse the data however required.
}
private void BleDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
{
Debug.Log("BleDevice_ConnectionStatusChanged: " + sender.ConnectionStatus);
if (sender.ConnectionStatus == BluetoothConnectionStatus.Connected) {
connected = true;
writeCommand();
}
}
private void BleDevice_GattServicesChanged(BluetoothLEDevice sender, object args)
{
Debug.Log("Count increased:" +sender.GattServices.Count);
}
private async void writeCommand()
{
Debug.Log("writeCommand");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
if (characteristic.Uuid.ToString().Equals(commandCharacteristic))
{
Debug.Log("command characteristic found");
var writer = new DataWriter();
// WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle
writer.WriteByte(0x01);
writer.WriteByte(0x03);
writer.WriteByte(0x02);
writer.WriteByte(0x01);
writer.WriteByte(0x01);
GattCommunicationStatus writeStatus = await characteristic.WriteValueAsync(writer.DetachBuffer());
if (writeStatus == GattCommunicationStatus.Success)
{
// Successfully wrote to device
Debug.Log("successfullly wrote characteristic");
vibrate();
}
}
}
}
}
}
private async void vibrate()
{
Debug.Log("writeCommand");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
if (characteristic.Uuid.ToString().Equals(commandCharacteristic))
{
Debug.Log("command characteristic found");
var writer = new DataWriter();
// WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle
writer.WriteByte(0x03);
writer.WriteByte(0x01);
writer.WriteByte(0x02);
GattCommunicationStatus writeStatus = await characteristic.WriteValueAsync(writer.DetachBuffer());
if (writeStatus == GattCommunicationStatus.Success)
{
// Successfully wrote to device
Debug.Log("successfullly wrote characteristic");
unlockCommand();
}
}
}
}
}
}
private async void unlockCommand()
{
Debug.Log("unlockCommand");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
if (characteristic.Uuid.ToString().Equals(commandCharacteristic))
{
Debug.Log("command characteristic found");
var writer = new DataWriter();
// WriteByte used for simplicity. Other commmon functions - WriteInt16 and WriteSingle
writer.WriteByte(0x0a);
writer.WriteByte(0x01);
writer.WriteByte(0x02);
GattCommunicationStatus writeStatus = await characteristic.WriteValueAsync(writer.DetachBuffer());
if (writeStatus == GattCommunicationStatus.Success)
{
// Successfully wrote to device
Debug.Log("successfullly wrote characteristic");
connectServices();
}
}
}
}
}
}
private async void connectServices() {
Debug.Log("connect services");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
//if (characteristic.Uuid.ToString().Equals(ClassifierEventCharacteristic))
{
Debug.Log("ClassifierEventCharacteristic");
if (properties.HasFlag(GattCharacteristicProperties.Indicate))
{
Debug.Log("indicate");
GattReadClientCharacteristicConfigurationDescriptorResult result = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();
if (result.Status == GattCommunicationStatus.Success)
{
if (result.ClientCharacteristicConfigurationDescriptor != GattClientCharacteristicConfigurationDescriptorValue.Indicate)
{
Debug.Log("indicate write success");
// Server has been informed of clients interest.
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
}
else {
Debug.Log("descriptor value == indicate ");
}
Debug.Log("GattCommunicationStatus.Success");
characteristic.ValueChanged += Characteristic_IndicateChanged;
}
else {
Debug.Log("characteristic connection failed");
}
}
}
}
}
//connectNotificationServices();
}
}
private async void connectNotificationServices()
{
Debug.Log("connect services");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
//if (characteristic.Uuid.ToString().Equals(ClassifierEventCharacteristic))
{
Debug.Log("ClassifierEventCharacteristic");
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
Debug.Log("notify");
GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
Debug.Log("notify write success");
// Server has been informed of clients interest.
characteristic.ValueChanged += Characteristic_ValueChanged;
}
}
}
}
}
}
}
private async void connectServicesOld()
{
Debug.Log("Yayyyyyy! Myo connected");
Debug.Log("Services:" + bleDevice.GattServices.Count);
if (bleDevice.GattServices.Count > 0)
{
foreach (GattDeviceService service in bleDevice.GattServices)
{
Debug.Log("service.Uuid: " + service.Uuid);
var gattCharacteristics = service.GetAllCharacteristics();
foreach (GattCharacteristic characteristic in gattCharacteristics)
{
Debug.Log("characteristic.Uuid: " + characteristic.Uuid);
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
// This characteristic supports reading from it.
GattReadResult result1 = await characteristic.ReadValueAsync();
if (result1.Status == GattCommunicationStatus.Success)
{
var reader = DataReader.FromBuffer(result1.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
Debug.Log(input);
// Utilize the data as needed
}
}
//if (characteristic.Uuid.ToString().Equals(ClassifierEventCharacteristic))
//{
// Debug.Log("ClassifierEventCharacteristic");
// if (properties.HasFlag(GattCharacteristicProperties.Notify))
// {
// Debug.Log("notify");
// GattCommunicationStatus status = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
//GattClientCharacteristicConfigurationDescriptorValue.Notify);
// if (status == GattCommunicationStatus.Success)
// {
// Debug.Log("notify write success");
// // Server has been informed of clients interest.
// characteristic.ValueChanged += Characteristic_ValueChanged;
// }
// }
if (properties.HasFlag(GattCharacteristicProperties.Indicate))
{
Debug.Log("indicate");
GattReadClientCharacteristicConfigurationDescriptorResult result = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();
if (result.Status == GattCommunicationStatus.Success &&
result.ClientCharacteristicConfigurationDescriptor != GattClientCharacteristicConfigurationDescriptorValue.Indicate)
{
Debug.Log("indicate write success");
// Server has been informed of clients interest.
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
characteristic.ValueChanged += Characteristic_IndicateChanged;
}
}
}
}
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment