public void Subscribe() { if (this.debugOutput) { Debug.Log("*** BLE Subscribe"); } BluetoothLEHardwareInterface.SubscribeCharacteristic(this.uuids[this.connectedDevice], this.serviceUUID, this.subscribeUUID, new Action <string>(this.Subscribed), new Action <string, byte[]>(this.SubResult)); }
public void SubscribeCharacteristic( string name, string service, string characteristic, Action <string> notificationAction, Action <string, byte[]> action ) { BluetoothLEHardwareInterface.SubscribeCharacteristic(name, service, characteristic, notificationAction, action); }
public void OnSubscribeClick(int buttonID) { if (buttonID >= 0 && buttonID < 4) { DeviceObject device = FoundDeviceListScript.DeviceAddressList[buttonID]; string subscribedService = Services[buttonID]; string subscribedCharacteristic = Characteristics[buttonID]; if (!string.IsNullOrEmpty(subscribedService) && !string.IsNullOrEmpty(subscribedCharacteristic)) { BluetoothLEHardwareInterface.Log("subscribing to: " + subscribedService + ", " + subscribedCharacteristic); BluetoothLEHardwareInterface.SubscribeCharacteristic(device.Address, subscribedService, subscribedCharacteristic, null, (characteristic, bytes) => { BluetoothLEHardwareInterface.Log("received data: " + characteristic); }); } } }
IEnumerator telemetryCoroutine() { BluetoothLEHardwareInterface.SubscribeCharacteristic( die.address, "6E401000-B5A3-F393-E0A9-E50E24DCCA9E", "6E401001-B5A3-F393-E0A9-E50E24DCCA9E", null, OnTelemetryData); yield return(new WaitForSeconds(0.5f)); BluetoothLEHardwareInterface.WriteCharacteristic( die.address, "6E401000-B5A3-F393-E0A9-E50E24DCCA9E", "6E401002-B5A3-F393-E0A9-E50E24DCCA9E", new byte[1] { 1 }, 1, false, null); }
void StartNextSubscribeToCharacteristic() { Die nextToSub = _dice.Values.FirstOrDefault(d => d.state == Die.State.Connected); if (nextToSub != null) { nextToSub.state = Die.State.Subscribing; // Set timeout... nextToSub.startTime = Time.time; // And subscribe! BluetoothLEHardwareInterface.SubscribeCharacteristic( nextToSub.address, serviceGUID, subscribeCharacteristic, OnCharacteristicSubscriptionChanged, (charac, data) => OnCharacteristicData(nextToSub.address, data)); } // Else no more subscription pending }
public void OnSubscribeClick(int buttonID) { if (buttonID >= 0 && buttonID < 4) { DeviceObject device = FoundDeviceListScript.DeviceAddressList[buttonID]; string subscribedService = Services[buttonID]; string subscribedCharacteristic = Characteristics[buttonID]; if (Connected[buttonID]) { BluetoothLEHardwareInterface.Log("subscribing to: " + subscribedService + ", " + subscribedCharacteristic); BluetoothLEHardwareInterface.SubscribeCharacteristic(device.Address, subscribedService, subscribedCharacteristic, null, (characteristic, bytes) => { string s = ASCIIEncoding.UTF8.GetString(bytes); //int ID = s[0]; //ID -= 49; Text button = ReceivedData[buttonID]; button.text = s; BluetoothLEHardwareInterface.Log("received data: " + characteristic); }); } } }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { if (name == "SmartInsoleL") { device_left.Name = name; device_left.Address = address; device_left.State = DEVICE_STATE.FOUND; } else if (name == "SmartInsoleR") { device_right.Name = name; device_right.Address = address; device_right.State = DEVICE_STATE.FOUND; } if (device_right.State == DEVICE_STATE.FOUND && device_left.State == DEVICE_STATE.FOUND) { BluetoothLEHardwareInterface.StopScan(); SetState(States.Connect, 0.5f); } }, null); break; case States.Connect: BluetoothLEHardwareInterface.ConnectToPeripheral(device_left.Address, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { device_left.FoundSubscribeID = device_left.FoundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); device_left.FoundWriteID = device_left.FoundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (device_left.FoundSubscribeID && device_left.FoundWriteID) { device_left.State = DEVICE_STATE.CONNECTED; SetState(States.Subscribe, 0.5f); } } }); BluetoothLEHardwareInterface.ConnectToPeripheral(device_right.Address, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { device_right.FoundSubscribeID = device_right.FoundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); device_right.FoundWriteID = device_right.FoundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (device_right.FoundSubscribeID && device_right.FoundWriteID) { device_right.State = DEVICE_STATE.CONNECTED; SetState(States.Subscribe, 0.5f); } } }); break; case States.Subscribe: BluetoothLEHardwareInterface.SubscribeCharacteristic(device_left.Address, FullUUID(ServiceUUID), FullUUID(SubscribeCharacteristic), null, (characteristic, bytes) => { //string s = ASCIIEncoding.UTF8.GetString(bytes); //left_foot_data.text = s; device_left.DataBytes = ASCIIEncoding.UTF8.GetString(bytes); device_left.State = DEVICE_STATE.SUBSCRIBED; device_left.NewData = true; SetState(States.None, 2f); }); BluetoothLEHardwareInterface.SubscribeCharacteristic(device_right.Address, FullUUID(ServiceUUID), FullUUID(SubscribeCharacteristic), null, (characteristic, bytes) => { //string s = ASCIIEncoding.UTF8.GetString(bytes); //right_foot_data.text = s; device_right.DataBytes = ASCIIEncoding.UTF8.GetString(bytes); device_right.State = DEVICE_STATE.SUBSCRIBED; device_right.NewData = true; SetState(States.None, 2f); }); _connected = true; break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; }); } break; } } } }
void OnGUI() { GUI.skin = skin; if (GUI.Button(new Rect(10, 0, 600, 100), "DeInitialize")) { BluetoothLEHardwareInterface.DeInitialize(null); } if (GUI.Button(new Rect(10, 100, 300, 50), "Initialize Central")) { bluetoothDeviceScript = BluetoothLEHardwareInterface.Initialize(true, false, null, null); } if (GUI.Button(new Rect(10, 150, 300, 50), "Scan for 1851")) { BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(new string[] { serviceUUID }, null); } if (GUI.Button(new Rect(10, 200, 300, 50), "Scan for Any")) { BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null); } if (GUI.Button(new Rect(10, 250, 300, 50), "Retrieve Connected")) { BluetoothLEHardwareInterface.RetrieveListOfPeripheralsWithServices(new string[] { serviceUUID }, null); } if (GUI.Button(new Rect(10, 300, 300, 50), "Stop Scan")) { BluetoothLEHardwareInterface.StopScan(); } if (GUI.Button(new Rect(10, 350, 300, 50), "Connect") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { BluetoothLEHardwareInterface.ConnectToPeripheral(bluetoothDeviceScript.DiscoveredDeviceList[0], null, null, null); } if (GUI.Button(new Rect(10, 400, 300, 50), "Disconnect") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { BluetoothLEHardwareInterface.DisconnectPeripheral(bluetoothDeviceScript.DiscoveredDeviceList[0], null); } if (GUI.Button(new Rect(10, 450, 300, 50), "Read Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { BluetoothLEHardwareInterface.ReadCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null); } if (GUI.Button(new Rect(10, 500, 300, 50), "Write Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { if (data == null) { data = new byte[64]; for (int i = 0; i < 64; ++i) { data[i] = (byte)i; } } BluetoothLEHardwareInterface.WriteCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, data, data.Length, true, null); } if (GUI.Button(new Rect(10, 550, 300, 50), "Subscribe Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { BluetoothLEHardwareInterface.SubscribeCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null, null); } if (GUI.Button(new Rect(10, 600, 300, 50), "UnSubscribe Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0) { BluetoothLEHardwareInterface.UnSubscribeCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null); } if (GUI.Button(new Rect(310, 100, 300, 100), "Initialize Peripheral")) { BluetoothLEHardwareInterface.Initialize(false, true, null, null); } if (GUI.Button(new Rect(310, 200, 300, 100), "Create Service\nand Characteristic")) { BluetoothLEHardwareInterface.PeripheralName("Test Device"); if (data == null) { data = new byte[64]; for (int i = 0; i < 64; ++i) { data[i] = (byte)i; } } BluetoothLEHardwareInterface.CreateCharacteristic(characteristicUUID, BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyRead | BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyWrite | BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyNotify, BluetoothLEHardwareInterface.CBAttributePermissions.CBAttributePermissionsReadable | BluetoothLEHardwareInterface.CBAttributePermissions.CBAttributePermissionsWriteable, null, 0, null); BluetoothLEHardwareInterface.CreateService(serviceUUID, true, null); } if (GUI.Button(new Rect(310, 300, 300, 100), "Start Advertising")) { BluetoothLEHardwareInterface.StartAdvertising(null); } if (GUI.Button(new Rect(310, 400, 300, 100), "Stop Advertising")) { BluetoothLEHardwareInterface.StopAdvertising(null); } if (GUI.Button(new Rect(310, 500, 300, 100), "Update Characteristic Value")) { for (int i = 0; i < data.Length; ++i) { data[i] = (byte)(data[i] + 1); } BluetoothLEHardwareInterface.UpdateCharacteristicValue(characteristicUUID, data, data.Length); } }
//workflow: //(1) scan for devices //(2) if device found, connect to device //(3) connect successful, scan for services //(4) service found, scan for characteristics //(5) got characteristics, get value for characteristic // Update is called once per frame void Update() { // do some stuff with the timeout so as to // not do two things at once if (timeout > 0f) { timeout -= Time.deltaTime; if (timeout <= 0f) { timeout = 0f; switch (state) { case States.None: Debug.Log("none"); break; case States.Scan: //(1) scan for devices Debug.Log("scanning"); // scan peripherals for peripherals with serviceUUID of serviceUUID = "2220" BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(new [] { ServiceUUID }, (address, name) => { // callback with adress and name Debug.Log("addr" + address + "name" + name); // GET NAME OF RFDUINO if (name.Contains(DeviceName)) { deviceAddress = address; // stop scan if we find the arduino BluetoothLEHardwareInterface.StopScan(); setState(States.Connect, 0.5f); } }, (address, name, rssi, bytes) => { //callback with address, name and advertising info Debug.Log("advertising info addr" + address + " name: " + name + " bytes " + bytes); }); break; case States.Connect: // (2) if device found, connect to device foundSubscribeID = false; Debug.Log("connecting"); // no callback for connect or service action, because each are enumerated and would have to carefully // set timeouts for all of them - ie: connect would call service actin for every service found, // every service found would call charactersitic action for every characteristic it has // ultimately, we only care about read characteristic BluetoothLEHardwareInterface.ConnectToPeripheral(deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => { // characterstic action foundSubscribeID = foundSubscribeID || IsEqual(characteristicUUID, SubscribeUUID); if (foundSubscribeID) { Debug.Log("connected"); connected = true; setState(States.Subscribe, 2f); } }); break; case States.Subscribe: //service found, subscribe to characteristics // which one ?! use subscribecharacteristic NOT readcharacteristic for if characteristic value will change // which eventually it will because sending different packets of data //DataScript d = gameObject.GetComponent<DataScript> (); Debug.Log("subscribing"); BluetoothLEHardwareInterface.SubscribeCharacteristic(deviceAddress, ServiceUUID, SubscribeUUID, (notification) => { //notificationAction Debug.Log("notification action is " + notification); }, (characteristicUUID, bytes) => { //action Debug.Log("subscribed"); string s = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length); Debug.Log("value changed, data: " + s); bool dataNonZero = d.receiveData(s); Debug.Log(dataNonZero.ToString()); dataBytes = bytes; setState(States.Subscribed, 10f); }); break; case States.Subscribed: Debug.Log("subscribed"); break; case States.Disconnect: BluetoothLEHardwareInterface.DisconnectPeripheral(deviceAddress, (address) => { BluetoothLEHardwareInterface.Log("1"); BluetoothLEHardwareInterface.DeInitialize(() => { connected = false; setState(States.None, 10f); }); }); break; } } } }
//handles Connect //connect the device as a peripheral, and set up the characteristics for I/O properly public void OnConnect(string dName, string dAddress) { _connectedName = (string)dName.Clone(); _connectedAddress = (string)dAddress.Clone(); if (!_connecting) { //perform a connection only if it is not doing it if (_connected) { //if already connected, disconnect it if (_connectedAddress != null) { BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null); } _connected = false; } else { _readFound = false; _writeFound = false; //connect to the device with the address provided BluetoothLEHardwareInterface.ConnectToPeripheral(_connectedAddress, (address) => {//gets called when the connection is successful _connectedAddress = address; _connected = true; _connecting = false; _bleManager.IndicateConnected(dName, dAddress); //let the manager know it is connected //stop scanning if a connection is established BluetoothLEHardwareInterface.StopScan(); }, (address, serviceUUID) => {//gets called for each service the device supports BluetoothLEHardwareInterface.Log(_connectedName + " supports service: " + serviceUUID); }, (address, serviceUUID, characteristicUUID) => {//gets called for each characteristic the device service supports BluetoothLEHardwareInterface.Log(serviceUUID + " supports characteristic: " + characteristicUUID); if (serviceUUID.ToUpper().CompareTo(_serviceUUID.ToUpper()) == 0) { //the _serviceUUID is a hardware-specific value indicating a certain collection of characteristics, // i.e., different from hardware to hardware if (characteristicUUID.ToUpper().CompareTo(_characteristicUUID.ToUpper()) == 0) { //Bean has 5 characteristics for 2-way communication, this code uses the first one as write _writeFound = true; } else if (characteristicUUID.ToUpper().CompareTo(_characteristicUUID2.ToUpper()) == 0) { //Bean has 5 charateristics for 2-way communication, this code uses the second one as read _readFound = true; //subscribe to the charateristic so the code will be notified if a change happens BluetoothLEHardwareInterface.SubscribeCharacteristic(_connectedAddress, _serviceUUID, _characteristicUUID2, (theOtherCharacteristicUUID) => { //gets called when a notification occurs }, (theOtherCharacteristicUUID, values) => { //gets called when the charateristic value is updated by the peripheral, provides access to the data (values) _bleManager.IndicateDataReceived(theOtherCharacteristicUUID, values); } ); } } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility _connected = false; } ); _connecting = true; } } }
void ScanForPM5Ergs() { StringComparison comp = StringComparison.OrdinalIgnoreCase; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(new string[] { toLongUUID("0030") }, (address, name) => { if (name.Contains("PM5", comp)) { output.text = "Found " + name; output1.text = "Addr: " + address; BluetoothLEHardwareInterface.ConnectToPeripheral(address, (addressPeriferal) => {}, (addressPeriferal, serviceUUID) => {}, (addressPeriferal, serviceUUID, characteristicUUID) => { // This should be C2 PM5 primary service Action <string, byte[]> actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntryGeneric; if (isShortCharacteristic(characteristicUUID, "0031")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry31; } else if (isShortCharacteristic(characteristicUUID, "0032")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry32; } else if (isShortCharacteristic(characteristicUUID, "0033")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry33; } else if (isShortCharacteristic(characteristicUUID, "0035")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry35; } else if (isShortCharacteristic(characteristicUUID, "0036")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry36; } else if (isShortCharacteristic(characteristicUUID, "003A")) { actionSuscribeCharacteristic = manageBufferPM5C2Erg.unPackageErgEntry3A; } BluetoothLEHardwareInterface.SubscribeCharacteristic(address, serviceUUID, characteristicUUID, actionSuscribeCharacteristic); // PM5Util.SuscribeC2characteristic(characteristicUUID); // PM5Util.SuscribeC2characteristic(characteristics[1],"ergData",manageBufferPM5C2Erg.unPackageErgEntry32); // PM5Util.SuscribeC2characteristic(characteristics[2],"ergData",manageBufferPM5C2Erg.unPackageErgEntry33); // PM5Util.SuscribeC2characteristic(characteristics[5],"ergData",manageBufferPM5C2Erg.unPackageErgEntry3A); // // called every stroke // PM5Util.SuscribeC2characteristic(characteristics[3],"strokeData",manageBufferPM5C2Erg.unPackageErgEntry35); // PM5Util.SuscribeC2characteristic(characteristics[4],"ergData",manageBufferPM5C2Erg.unPackageErgEntry36); /* * // _connectedID = addressPeriferal; * _serviceUUID = serviceUUID; * _characteristicUUID = characteristicUUID; * output1.text = String.Format("{0}: {1} {2} {3}",characteristicUUID,ergServiceUUID,addressPeriferal,characteristicUUID.ToString()); * output.text = characteristicUUID; * // We are connected, now request a read * BluetoothLEHardwareInterface.ReadCharacteristic (_connectedID,_serviceUUID,_characteristicUUID, * // actionReadErgData * (string nameCharacteristic, byte[] data) => { * // File.WriteAllBytes("Foo.txt", data); // Requires System.IO * * output.text = String.Format("{0}|{1}|{2}|{3}",data[0],data[1],data[2],data[3]); * ErgData erg = ErgData.FromBytes(data); * // OnErgData(erg); * factoryCommunication.OnErgData(erg); * output1.text = String.Format("{0}",erg.ToString()); * // output1.text = String.Format("We got this {0} {1}",BitConverter.IsLittleEndian,data.Length); * BluetoothLEHardwareInterface.ReadCharacteristic (_connectedID,_serviceUUID,_characteristicUUID, actionReadErgData); * } * * * * ); * // */ }); } }); }
public void ConnectToDie(Die die, System.Action <Die> dieConnectedCallback, System.Action <Die> dieDisconnectedCallback) { if (!die.connected && _state == CentralState.Idle) { _state = CentralState.Connecting; connectingStartTime = Time.time; bool readCharacDiscovered = false; bool writeCharacDiscovered = false; System.Action gotReadOrWriteCharacteristic = () => { // Do we have both read and write access? If so we're good to go! if (readCharacDiscovered && writeCharacDiscovered) { // If somehow we've timed out, skip this. if (_state == CentralState.Connecting) { // We're ready to go die.Connect(this); _state = CentralState.Idle; if (dieConnectedCallback != null) { dieConnectedCallback(die); } if (onDieConnected != null) { onDieConnected(die); } foreach (var client in clients) { client.OnNewDie(die); } } } }; System.Action <string, string, string> onCharacteristicDiscovered = (ad, serv, charac) => { // Check for the service guid to match that for our dice (it's the Simblee one) if (ad == die.address && serv.ToLower() == serviceGUID.ToLower()) { // Check the discovered characteristic if (charac.ToLower() == subscribeCharacteristic.ToLower()) { // It's the read characteristic, subscribe to it! System.Action <string, byte[]> onDataReceived = (dev, data) => { die.DataReceived(data); }; if (virtualBluetooth == null || !virtualBluetooth.IsVirtualDie(die.address)) { BluetoothLEHardwareInterface.SubscribeCharacteristic(die.address, serviceGUID, subscribeCharacteristic, null, onDataReceived); } else { virtualBluetooth.SubscribeCharacteristic(die.address, serviceGUID, subscribeCharacteristic, null, onDataReceived); } readCharacDiscovered = true; gotReadOrWriteCharacteristic(); } else if (charac.ToLower() == writeCharacteristic.ToLower()) { // It's the write characteristic, remember that writeCharacDiscovered = true; gotReadOrWriteCharacteristic(); } // Else we don't care about this characteristic } }; System.Action <string> dieDisconnected = (ad) => { if (ad == die.address) { if (dieDisconnectedCallback != null) { dieDisconnectedCallback(die); } if (onDieDisconnected != null) { onDieDisconnected(die); } die.Disconnect(); } }; if (virtualBluetooth == null || !virtualBluetooth.IsVirtualDie(die.address)) { BluetoothLEHardwareInterface.ConnectToPeripheral(die.address, null, null, onCharacteristicDiscovered, dieDisconnected); } else { virtualBluetooth.ConnectToPeripheral(die.address, null, null, onCharacteristicDiscovered, dieDisconnected); } } else { Debug.LogError("Central is not ready to connect, current state is " + _state); } }