Exemplo n.º 1
0
    void ReadString()
    {
        BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
            print(Encoding.ASCII.GetString(bytes));

            BluetoothLEHardwareInterface.Log("read Succeeded");
        });
    }
Exemplo n.º 2
0
    void ReadString()
    {
        //TODO: adapt for multiple config
        BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressBlue, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
            print(Encoding.ASCII.GetString(bytes));

            BluetoothLEHardwareInterface.Log("read Succeeded");
        });
    }
Exemplo n.º 3
0
 public void ReadCharacteristic(
     string name,
     string service,
     string characteristic,
     Action <string, byte[]> action
     )
 {
     BluetoothLEHardwareInterface.ReadCharacteristic(name, service, characteristic, action);
 }
Exemplo n.º 4
0
 public void OnClick()
 {
     // is_busy_global = true;
     Debug.Log("TOAN101: CLicking " + serviceUUID + " " + characteristicUUID);
     if (BLEManager.I.IsEqual(characteristicUUID, "2a9d") ||
         BLEManager.I.IsEqual(characteristicUUID, "2a03") ||
         BLEManager.I.IsEqual(characteristicUUID, "2a05")
         )
     {
         BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(address, serviceUUID, characteristicUUID,
                                                                               (noti, noti2) =>
         {
             is_get_info = true;
             // is_busy_global = false;
             Debug.Log("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address);
             BLEManager.I.MyLog("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address);
         },
                                                                               (address, characteristicUUID, bytes) =>
         {
             Debug.Log("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address);
             BLEManager.I.MyLog("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address);
             string data = "";
             foreach (var b in bytes)
             {
                 data += b.ToString("X") + " ";
             }
             TEXT2.text  = data;
             TEXT1.text += " ***** ";
             is_get_info = true;
             //  is_busy_global = false;
         }
                                                                               );
     }
     else
     {
         BluetoothLEHardwareInterface.ReadCharacteristic(address, serviceUUID, characteristicUUID, (characteristicUUID2, bytes) =>
         {
             Debug.Log("TOAN189: ReadCharacteristic to " + characteristicUUID2 + " : " + "OK");
             BLEManager.I.MyLog("TOAN189: ReadCharacteristic to " + characteristicUUID2 + " : " + "OK");
             string data = "";
             foreach (var b in bytes)
             {
                 data += b.ToString("X") + " ";
             }
             TEXT2.text  = data;
             is_get_info = true;
             // is_busy_global = false;
         });
     }
 }
Exemplo n.º 5
0
    void initActions()
    {
        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);
        };
    }
Exemplo n.º 6
0
    void GetHardwareInfo(string _mac)
    {
        Debug.Log("Get hardware info from: " + _mac);

        BluetoothLEHardwareInterface.ReadCharacteristic(_mac, "FFC0", "FFC4", (_channel, _data) =>
        {
#if UNITY_ANDROID
            _channel = _channel.Substring(4, 4).ToUpper();
#endif
            if ("FFC4" == _channel)
            {
                firmwareVersion = GetFirmwareVersion(_data);
                hardwareVersion = GetHardwareVersion(_data);
                Debug.Log("Firmware Version: " + firmwareVersion);
                Debug.Log("Hardware Version: " + hardwareVersion);
            }
        });
    }
 public void GetAllCharacteristics(string address, string serviceUUID, string characteristicUUID)
 {
     if (IsEqual(characteristicUUID, "2a9d") ||
         IsEqual(characteristicUUID, "2a03") ||
         IsEqual(characteristicUUID, "2a05")
         )
     {
         BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(address, serviceUUID, characteristicUUID,
                                                                               (noti, noti2) =>
         {
             is_get_info = true;
             Debug.Log("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address);
         },
                                                                               (address2, characteristicUUID2, bytes) =>
         {
             Debug.Log("TOAN5555: SubscribeCharacteristicWithDeviceAddress to " + address2);
             string data = "";
             foreach (var b in bytes)
             {
                 data += b.ToString("X") + " ";
             }
             DICT_OBTAINED.Add(characteristicUUID, new characteristicUUIDInfo(address, serviceUUID, characteristicUUID, data, bytes));
             is_get_info = true;
         }
                                                                               );
     }
     else
     {
         BluetoothLEHardwareInterface.ReadCharacteristic(address, serviceUUID, characteristicUUID, (characteristicUUID2, bytes) =>
         {
             Debug.Log("TOAN189: ReadCharacteristic to " + characteristicUUID2 + " : " + "OK");
             string data = "";
             foreach (var b in bytes)
             {
                 data += b.ToString("X") + " ";
             }
             DICT_OBTAINED.Add(characteristicUUID, new characteristicUUIDInfo(address, serviceUUID, characteristicUUID, data, bytes));
             is_get_info = true;
         });
     }
 }
Exemplo n.º 8
0
    private void RetrieveTelemetry()
    {
        if (PendingReads == 0 && ReadTimer > 0.25f)
        {
            ReadTimer    = 0.0f;
            PendingReads = 3;

            BluetoothLEHardwareInterface.ReadCharacteristic(ConnectedToAdr, FullUUID(TelemetryServiceUID), FullUUID(YawTelemetryCharacteristicUID),
                                                            (uuid, data) =>
            {
                PendingReads--;
                if (data.Length == 4)
                {
                    CurYaw = BitConverter.ToSingle(data, 0);
                }
            });

            BluetoothLEHardwareInterface.ReadCharacteristic(ConnectedToAdr, FullUUID(TelemetryServiceUID), FullUUID(PitchTelemetryCharacteristicUID),
                                                            (uuid, data) =>
            {
                PendingReads--;
                if (data.Length == 4)
                {
                    CurPitch = BitConverter.ToSingle(data, 0);
                }
            });

            BluetoothLEHardwareInterface.ReadCharacteristic(ConnectedToAdr, FullUUID(TelemetryServiceUID), FullUUID(RollTelemetryCharacteristicUID),
                                                            (uuid, data) =>
            {
                PendingReads--;
                if (data.Length == 4)
                {
                    CurRoll = BitConverter.ToSingle(data, 0);
                }
            });
        }
        ReadTimer += Time.deltaTime;
    }
Exemplo n.º 9
0
    // 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:
                    Debug.Log("right before the scan");
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) =>
                    {
                        // if your device does not advertise the rssi and manufacturer specific data
                        // then you must use this callback because the next callback only gets called
                        // if you have manufacturer specific data

                        if (!_rssiOnly)
                        {
                            if (name.Contains(DeviceName))
                            {
                                BluetoothLEHardwareInterface.StopScan();

                                // found a device with the name we want
                                // this example does not deal with finding more than one
                                _deviceAddress = address;
                                SetState(States.Connect, 0.5f);
                            }
                        }
                    }, (address, name, rssi, bytes) =>
                    {
                        // use this one if the device responses with manufacturer specific data and the rssi

                        if (name.Contains(DeviceName))
                        {
                            if (_rssiOnly)
                            {
                                _rssi = rssi;
                            }
                            else
                            {
                                BluetoothLEHardwareInterface.StopScan();

                                // found a device with the name we want
                                // this example does not deal with finding more than one
                                _deviceAddress = address;
                                SetState(States.Connect, 0.5f);
                            }
                        }
                    }, _rssiOnly);     // this last setting allows RFduino to send RSSI without having manufacturer data

                    if (_rssiOnly)
                    {
                        SetState(States.ScanRSSI, 0.5f);
                    }
                    break;

                case States.ScanRSSI:
                    break;

                case States.Connect:
                    // set these flags
                    _foundSubscribeID = false;
                    _foundWriteID     = false;

                    // note that the first parameter is the address, not the name. I have not fixed this because
                    // of backwards compatiblity.
                    // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of
                    // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout
                    // large enough that it will be finished enumerating before you try to subscribe or do any other operations.
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) =>
                    {
                        if (IsEqual(serviceUUID, ServiceUUID))
                        {
                            _foundSubscribeID = _foundSubscribeID || IsEqual(characteristicUUID, ActionCharacteristic);

                            // 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 (_foundSubscribeID)
                            {
                                _connected = true;
                                SetState(_action, 2f);
                            }
                        }
                    });
                    break;

                case States.Read:
                    Debug.Log("trying to read " + ActionCharacteristic);
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ActionCharacteristic, (characteristic, bytes) =>
                    {
                        Debug.Log("read complete");
                        _state         = States.None;
                        _dataBytes     = bytes;
                        _actionSuccess = true;
                    });
                    break;

                case States.Subscribe:
                    Debug.Log("trying to subscribe " + ActionCharacteristic);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, ActionCharacteristic, null, (address, characteristicUUID, bytes) =>
                    {
                        // we don't have a great way to set the state other than waiting until we actually got
                        // some data back. For this demo with the rfduino that means pressing the button
                        // on the rfduino at least once before the GUI will update.
                        //_state = States.None;

                        // we received some data from the device
                        _dataBytes     = bytes;
                        _actionSuccess = true;
                    });
                    break;

                case States.Write:
                    BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ServiceUUID, ActionCharacteristic, _dataToWrite, _dataToWrite.Length, true, (characteristicUUID) => {
                        BluetoothLEHardwareInterface.Log("Write Succeeded");
                        _actionSuccess = true;
                    });
                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, ActionCharacteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) =>
                        {
                            _connected = false;
                            _state     = States.Disconnected;
                        });
                    }
                    else
                    {
                        _state = States.Disconnected;
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 10
0
    // 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:
                    StatusMessage = "Scanning for " + DeviceName;

                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) =>
                    {
                        // if your device does not advertise the rssi and manufacturer specific data
                        // then you must use this callback because the next callback only gets called
                        // if you have manufacturer specific data

                        if (!_rssiOnly)
                        {
                            if (name.Contains(DeviceName))
                            {
                                StatusMessage = "Found " + name;

                                BluetoothLEHardwareInterface.StopScan();

                                // found a device with the name we want
                                // this example does not deal with finding more than one
                                _deviceAddress = address;
                                SetState(States.Connect, 0.5f);
                            }
                        }
                    }, (address, name, rssi, bytes) =>
                    {
                        // use this one if the device responses with manufacturer specific data and the rssi

                        if (name.Contains(DeviceName))
                        {
                            StatusMessage = "Found " + name;

                            if (_rssiOnly)
                            {
                                _rssi = rssi;
                            }
                            else
                            {
                                BluetoothLEHardwareInterface.StopScan();

                                // found a device with the name we want
                                // this example does not deal with finding more than one
                                _deviceAddress = address;
                                SetState(States.Connect, 0.5f);
                            }
                        }
                    }, _rssiOnly);     // this last setting allows RFduino to send RSSI without having manufacturer data

                    if (_rssiOnly)
                    {
                        SetState(States.ScanRSSI, 0.5f);
                    }
                    break;

                case States.ScanRSSI:
                    break;

                case States.Connect:
                    StatusMessage = "Connecting...";

                    // set these flags
                    _foundButtonUUID = false;
                    _foundLedUUID    = false;

                    // note that the first parameter is the address, not the name. I have not fixed this because
                    // of backwards compatiblity.
                    // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of
                    // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout
                    // large enough that it will be finished enumerating before you try to subscribe or do any other operations.
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) =>
                    {
                        StatusMessage = "Connected...";

                        if (IsEqual(serviceUUID, ServiceUUID))
                        {
                            StatusMessage = "Found Service UUID";

                            _foundButtonUUID = _foundButtonUUID || IsEqual(characteristicUUID, ButtonUUID);
                            _foundLedUUID    = _foundLedUUID || IsEqual(characteristicUUID, LedUUID);

                            // 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 (_foundButtonUUID && _foundLedUUID)
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);
                            }
                        }
                    });
                    break;

                case States.Subscribe:
                    StatusMessage = "Subscribing to characteristics...";

                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, ButtonUUID, (notifyAddress, notifyCharacteristic) =>
                    {
                        StatusMessage = "Waiting for user action (1)...";
                        _state        = States.None;

                        // read the initial state of the button
                        BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, (characteristic, bytes) =>
                        {
                            ProcessButton(bytes);
                        });
                    }, (address, characteristicUUID, bytes) =>
                    {
                        if (_state != States.None)
                        {
                            // some devices do not properly send the notification state change which calls
                            // the lambda just above this one so in those cases we don't have a great way to
                            // set the state other than waiting until we actually got some data back.
                            // The esp32 sends the notification above, but if yuor device doesn't you would have
                            // to send data like pressing the button on the esp32 as the sketch for this demo
                            // would then send data to trigger this.
                            StatusMessage = "Waiting for user action (2)...";

                            _state = States.None;
                        }

                        // we received some data from the device
                        ProcessButton(bytes);
                    });
                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    StatusMessage = "Commanded disconnect.";

                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) =>
                        {
                            StatusMessage = "Device disconnected";
                            BluetoothLEHardwareInterface.DeInitialize(() =>
                            {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() =>
                        {
                            _state = States.None;
                        });
                    }
                    break;
                }
            }
        }
    }
    // 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, deviceName) => {
                        if (deviceName.Contains(DeviceName))
                        {
                            SensorBugStatusMessage = "Found a SensorBug";

                            BluetoothLEHardwareInterface.StopScan();

                            PairingMessage.SetActive(false);
                            TopPanel.SetActive(true);

                            // found a device with the name we want
                            // this example does not deal with finding more than one
                            _deviceAddress = address;
                            SetState(States.Connect, 0.5f);
                        }
                    }, null, true);
                    break;

                case States.Connect:
                    SensorBugStatusMessage = "Connecting to SensorBug...";

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => {
                        var characteristic = GetCharacteristic(serviceUUID, characteristicUUID);
                        if (characteristic != null)
                        {
                            BluetoothLEHardwareInterface.Log(string.Format("Found {0}, {1}", serviceUUID, characteristicUUID));

                            characteristic.Found = true;

                            if (AllCharacteristicsFound)
                            {
                                _connected = true;
                                SetState(States.ReadPairingStatus, 3f);
                            }
                        }
                    }, (disconnectAddress) => {
                        SensorBugStatusMessage = "Disconnected from SensorBug";
                        Reset();
                        SetState(States.Scan, 1f);
                    });
                    break;

                case States.ReadPairingStatus:
                    SetState(States.WaitPairingStatus, 5f);
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, PairingManagementStatus.ServiceUUID, PairingManagementStatus.CharacteristicUUID, (characteristic, bytes) => {
                        if (bytes.Length >= 9)
                        {
                            SensorBugStatusMessage = string.Format("Status byte: {0}", bytes[8]);
                            if ((bytes[8] & 0x01) == 0x01)
                            {
                                // we are paired
                                // move on to configuring the accelerometer
                                SetState(States.ConfigureAccelerometer, 0.5f);
                            }
                            else
                            {
                                // we are not paired
                                // write the control register to trigger pairing
                                BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, PairingManagementStatus.ServiceUUID, PairingManagementStatus.CharacteristicUUID, new byte[] { 0x00 }, 1, true, (characteristic2) => {
                                    SetState(States.ReadPairingStatus, 0.5f);
                                });
                            }
                        }
                        else
                        {
                            SensorBugStatusMessage = "Error retrieving status from pairing SensorBug";
                        }
                    });
                    break;

                case States.WaitPairingStatus:
                    // if we got here we timed out waiting for pairing status
                    SetState(States.Disconnect, 0.5f);
                    break;

                case States.ConfigureAccelerometer:
                    SensorBugStatusMessage = "Configuring SensorBug Accelerometer...";
                    BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ConfigureAccelerometer.ServiceUUID, ConfigureAccelerometer.CharacteristicUUID, _accelerometerConfigureBytes, _accelerometerConfigureBytes.Length, true, (address) => {
                        SensorBugStatusMessage = "Configured SensorBug Accelerometer";
                        SetState(States.SubscribeToAccelerometer, 2f);
                    });
                    break;

                case States.SubscribeToAccelerometer:
                    SetState(States.SubscribingToAccelerometer, 5f);
                    SensorBugStatusMessage = "Subscribing to SensorBug Accelerometer...";
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, SubscribeAccelerometer.ServiceUUID, SubscribeAccelerometer.CharacteristicUUID, null, (deviceAddress, characteristric, bytes) => {
                        _state = States.None;
                        MiddlePanel.SetActive(true);

                        var sBytes             = BitConverter.ToString(bytes);
                        AccelerometerText.text = "Accelerometer: " + sBytes;
                    });
                    break;

                case States.SubscribingToAccelerometer:
                    // if we got here it means we timed out subscribing to the accelerometer
                    SetState(States.Disconnect, 0.5f);
                    break;

                case States.Disconnect:
                    SetState(States.Disconnecting, 5f);
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                            // since we have a callback for disconnect in the connect method above, we don't
                            // need to process the callback here.
                        });
                    }
                    else
                    {
                        Reset();
                        SetState(States.Scan, 1f);
                    }
                    break;

                case States.Disconnecting:
                    // if we got here we timed out disconnecting, so just go to disconnected state
                    Reset();
                    SetState(States.Scan, 1f);
                    break;
                }
            }
        }
    }
Exemplo n.º 12
0
    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);
        }
    }
Exemplo n.º 13
0
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;

                string state = _state.ToString();
                print("running state " + state);                 // + state); //+ _state.ToString ());// + _state.ToString());

                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    print("Scan running");

                    if (ConnectedLeft == null || !ConnectedLeft)
                    {
                        _deviceAddressLeft = "";
                    }

                    if (ConnectedRight == null || !ConnectedRight)
                    {
                        _deviceAddressRight = "";
                    }

                    print("Scan running");
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                        // if your device does not advertise the rssi and manufacturer specific data
                        // then you must use this callback because the next callback only gets called
                        // if you have manufacturer specific data

                        print("Found " + name);
                        if (!name.Contains("fruit"))
                        {
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && string.IsNullOrEmpty(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressRight) && !address.Equals(storedDeviceAddressLeft))
                        {
                            storedDeviceAddressRight = address;
                            _deviceAddressRight      = address;
                            RightName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && !address.Equals(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressLeft) && ConnectedLeft != null && !ConnectedLeft)
                        {
                            LeftName           = name;
                            _deviceAddressLeft = address;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressRight) && ConnectedRight != null && !ConnectedRight)
                        {
                            RightName           = name;
                            _deviceAddressRight = address;
                            ++found;
                        }
                        if (found >= 2 || _timeout < -4)
                        {
                            found = 0;
                            SetState(States.Connect, 0.5f);
                            BluetoothLEHardwareInterface.StopScan();
                        }
                    }, (address, name, rssi, bytes) => {
                        print("Found " + name);
                        if (string.IsNullOrEmpty(storedDeviceAddressLeft) && string.IsNullOrEmpty(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressRight) && !address.Equals(storedDeviceAddressLeft))
                        {
                            storedDeviceAddressRight = address;
                            _deviceAddressRight      = address;
                            RightName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && !address.Equals(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressLeft) && ConnectedLeft != null && !ConnectedLeft)
                        {
                            LeftName           = name;
                            _deviceAddressLeft = address;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressRight) && ConnectedRight != null && !ConnectedRight)
                        {
                            RightName           = name;
                            _deviceAddressRight = address;
                            ++found;
                        }
                        if (found >= 2 || _timeout < -4)
                        {
                            found = 0;
                            SetState(States.Connect, 0.5f);
                            BluetoothLEHardwareInterface.StopScan();
                        }
                    }, _rssiOnly);                     // this last setting allows RFduino to send RSSI without having manufacturer data


                    if (_rssiOnly)
                    {
                        SetState(States.ScanRSSI, 0.5f);
                    }
                    break;

                case States.ScanRSSI:
                    break;

                case States.Send:
                    //SendString ("Hello Scott");
                    ReadString();
                    SetState(States.Send, 0.5f);
                    break;


                case States.Connect:
                    // set these flags
                    _foundSubscribeID = false;
                    _foundWriteID     = false;

                    print("Connect Primary running for Left! " + LeftName);

                    print("Scott12: Connected LEFT: " + ConnectedLeft + " Connected Right " + ConnectedRight + " Device Address Left: " + _deviceAddressLeft + " Device Address Right: " + _deviceAddressRight);

                    if (ConnectedLeft == null)
                    {
                        ConnectedLeft = false;
                    }
                    if (ConnectedLeft || string.IsNullOrEmpty(_deviceAddressLeft))
                    {
                        SetState(States.ConnectSecondary, 0.1f);
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressLeft, (address) => {
                    },
                                                                     (address, serviceUUID) => {
                    },
                                                                     (address, serviceUUID, characteristicUUID) => {
                        print("connecting to characteristic Blue!" + characteristicUUID);
                        if (IsEqual(characteristicUUID, ReadCharacteristic))
                        {
                            //print ("subscribing . . . ");
                            print("Blue!: Device Address Blue: " + _deviceAddressLeft + "\n" +
                                  "Blue: Service UUID: " + serviceUUID + "/n" +
                                  "Blue: Read Characteristic: " + ReadCharacteristic + "\n");

//							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressLeft, serviceUUID, ReadCharacteristic, null, (address2, characteristicUUID2, bytes) => {
//								print ("Blue frame update");
//								ReactToInput (bytes, address2);
//
                            SetState(States.ConnectSecondary, 0.5f);
                            ConnectedLeft = true;
                        }
                    }, (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
                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });

                    break;

                case States.ConnectPrimary:
                    // set these flags
                    print("Connect Primary running for Left! " + LeftName);

                    if (ConnectedLeft == null)
                    {
                        ConnectedLeft = false;
                    }
                    if (ConnectedLeft || string.IsNullOrEmpty(_deviceAddressLeft))
                    {
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressLeft, (address) => {
                    },
                                                                     (address, serviceUUID) => {
                    },
                                                                     (address, serviceUUID, characteristicUUID) => {
                        print("connecting to characteristic Blue!" + characteristicUUID);
                        if (IsEqual(characteristicUUID, ReadCharacteristic))
                        {
                            //print ("subscribing . . . ");
                            print("Blue!: Device Address Blue: " + _deviceAddressLeft + "\n" +
                                  "Blue: Service UUID: " + serviceUUID + "/n" +
                                  "Blue: Read Characteristic: " + ReadCharacteristic + "\n");

                            //							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressLeft, serviceUUID, ReadCharacteristic, null, (address2, characteristicUUID2, bytes) => {
                            //								print ("Blue frame update");
                            //								ReactToInput (bytes, address2);
                            //
                            //							SetState (States.ConnectSecondary, 0.5f);
                            ConnectedLeft = true;
                        }
                    }, (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
                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });

                    break;

                case States.ConnectSecondary:
                    _foundSubscribeID = false;
                    _foundWriteID     = false;

                    print("Connect Secondary running for " + RightName);

                    if (ConnectedRight || string.IsNullOrEmpty(_deviceAddressRight))
                    {
                        //TODO: hook this up to normal mode
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressRight, null, null, (address2, serviceUUID2, characteristicUUID2) => {
                        //print("connecting to device");
                        //print(_deviceAddress);
                        //print(address);
                        print("connecting to characteristic " + characteristicUUID2);

                        /*if (IsEqual (characteristicUUID2, WriteCharacteristic)) {
                         *      SetState (States.None, 0.5f);
                         * } else */
                        if (IsEqual(characteristicUUID2, ReadCharacteristic))
                        {
//							print ("subscribing . . . ");
                            print("Red!: Device Address Red: " + _deviceAddressRight + "\n" +
                                  "Red: Service UUID: " + serviceUUID2 + "/n" +
                                  "Red: Read Characteristic: " + ReadCharacteristic + "\n");
//							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressRight, serviceUUID2, ReadCharacteristic, null, (address3, characteristicUUID3, bytes) => {
//								print ("Red frame update");
//								ReactToInput (bytes, address3);
//							});
                            print("connected right");
                            ConnectedRight = true;

                            //TODO: hook this up to normal mode
                        }
                    }, (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

                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });
                    break;

                case States.Subscribe:

                    if (ConnectedLeft && !subscribedLeft)
                    {
                        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, null, (address, characteristicUUID, bytes) => {
                            print("input recieved");
                            // we don't have a great way to set the state other than waiting until we actually got
                            // some data back. For this demo with the rfduino that means pressing the button
                            // on the rfduino at least once before the GUI will update.
                            _state = States.None;

                            // we received some data from the device
                            _dataBytes = bytes;
                        });
                        subscribedLeft = true;
                    }

                    if (ConnectedRight && !subscribedRight)
                    {
                        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddressRight, ServiceUUID, ReadCharacteristic, null, (address, characteristicUUID, bytes) => {
                            print("input recieved");
                            // we don't have a great way to set the state other than waiting until we actually got
                            // some data back. For this demo with the rfduino that means pressing the button
                            // on the rfduino at least once before the GUI will update.
                            _state = States.None;

                            // we received some data from the device
                            _dataBytes = bytes;
                        });
                        subscribedRight = true;
                    }
                    break;

                case States.ReadLeft:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressLeft);
                        if (reading)
                        {
                            SetState(States.ReadLeft, 0.01f);
                        }
                    });
                    //SetState (States.ReadLeft, 0.01f);
                    break;

                case States.ReadRight:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressRight, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressRight);
                        if (reading)
                        {
                            SetState(States.ReadRight, 0.01f);
                        }
                    });
                    //SetState (States.ReadRight, 0.01f);
                    break;

                case States.ReadBoth:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressRight, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressRight);
                        BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, (charUID, bits) => {
                            ReactToInput(bits, _deviceAddressLeft);
                            if (reading)
                            {
                                SetState(States.ReadBoth, 0.001f);
                            }
                        });
                    });
                    //SetState (States.ReadBoth, 0.02f);
                    break;


                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, null);
                    // no red support
                    SetState(States.DisconnectLeft, 4f);
                    break;

                case States.DisconnectLeft:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddressLeft, (address) => {});
                    break;

                case States.DisconnectRight:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddressRight, (address) => {});
                    break;
                }
            }
        }
        else
        {
            _timeout -= Time.deltaTime;

            if (_state == States.Scan && _timeout < -5.0f)
            {
                BluetoothLEHardwareInterface.StopScan();
                SetState(States.Connect, 0.1f);
            }
        }
    }