Exemplo n.º 1
0
 public void DeinitializeBluetooth()
 {
     BluetoothLEHardwareInterface.DeInitialize(() =>
     {
         Debug.Log("Bluetooth has shut down.");
     });
 }
Exemplo n.º 2
0
 // NOTE: The button that triggers this is for when you are running this code in the macOS
 // Unity Editor and have the experimental bluetooth support turned on. This is because I
 // how found it crashes less often when you deinitialize first. You must still use caution
 // and save your work often as it could still have issues.
 // MacOS editor support is experimental. I am working on trying to make it work better in
 // the editor.
 public void OnDeinitializeButton()
 {
     BluetoothLEHardwareInterface.DeInitialize(() =>
     {
         StatusMessage = "Deinitialize";
     });
 }
 private void ResetState(Action afterResetAction)
 {
     if (_peripheralParams.HasValue)
     {
         if (_connected)
         {
             logger.DebugLog("Disconnecting from peripheral with device address: " + _deviceAddress);
             BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                 logger.DebugLog("De-initializing bluetooth hardware interface");
                 BluetoothLEHardwareInterface.DeInitialize(() => {
                     ResetStateVars();
                     afterResetAction();
                 });
             });
         }
         else
         {
             logger.DebugLog("De-initializing bluetooth hardware interface");
             BluetoothLEHardwareInterface.DeInitialize(() => {
                 ResetStateVars();
                 afterResetAction();
             });
         }
     }
     else
     {
         ResetStateVars();
         afterResetAction();
     }
 }
Exemplo n.º 4
0
    public void StartScan(Callback Success, Callback Error)
    {
        m_ScanAndConnectSuccess = Success;
        m_ScanAndConnectError   = Error;

        m_ConnectCharacteristicUUID = new Dictionary <string, bool>();
        for (int i = 0; i < CharacteristicUUID.Length; i++)
        {
            m_ConnectCharacteristicUUID[CharacteristicUUID[i]] = false;
        }

        //Reset();
        BluetoothLEHardwareInterface.Initialize(true, false, () => {
            SetMode(eMode.ScanDevice);
        }, (error) =>
        {
            BluetoothLEHardwareInterface.Log("Error during initialize: " + error);
            if (error == "Bluetooth LE Not Enabled")
            {
                BluetoothLEHardwareInterface.DeInitialize(() =>
                {
                    BluetoothLEHardwareInterface.BluetoothEnable(true);
                    if (m_ScanAndConnectError != null)
                    {
                        m_ScanAndConnectError();
                    }
                });
            }
        });
    }
Exemplo n.º 5
0
        /// <summary>
        /// DeInitializes the BLE Service, so you can start once again. This will be called once application quits.
        /// </summary>
        private static void DeInitialize()
        {
            CheckIfInitialized();

            BluetoothLEHardwareInterface.DeInitialize(() =>
            {
                IsInitialized = false;
            });
        }
Exemplo n.º 6
0
 public void OnBack()
 {
     if (_scanning)
     {
         OnScan();              // this will stop scanning
     }
     BluetoothLEHardwareInterface.DeInitialize(() => {
     });
 }
Exemplo n.º 7
0
 private void OnApplicationQuit()
 {
     BluetoothLEHardwareInterface.StopScan();
     BluetoothLEHardwareInterface.DisconnectAll();
     BluetoothLEHardwareInterface.DeInitialize(() =>
     {
         Debug.Log("Bluetooth has shut down on application quit.");
     });
 }
Exemplo n.º 8
0
 public override void DisconnectDevice()
 {
     //need to disconnect and deinitialize and then finish it otherwise it won't be disconnected the right way.
     BluetoothLEHardwareInterface.DisconnectAll();
     ConnectDevice(adressFinal);
     BluetoothLEHardwareInterface.DeInitialize(() => { });
     BluetoothLEHardwareInterface.FinishDeInitialize();
     isConnected = false;
 }
    protected override void OnButtonClick(Button btn)
    {
        base.OnButtonClick(btn);

        switch (btn.name)
        {
        case "Bluetooth2StartFrameBtn":
            GuiController.Instance.SwitchWrapperWithScale(GuiFrameID.StartFrame, false);
            break;

        case "BluetoothCentralBtn":
            InitializeBluetooth(true);
            break;

        case "BluetoothPeripheralBtn":
            InitializeBluetooth(false);
            break;

        case "BackFromContentBtn":
            scaning = false;
            BluetoothLEHardwareInterface.RemoveCharacteristics();
            BluetoothLEHardwareInterface.RemoveServices();
            BluetoothLEHardwareInterface.DeInitialize(() =>
            {
                MyDebug.LogGreen("DeInitialize Success!");
            });
            CommonTool.GuiHorizontalMove(bluetoothCategoryContent, Screen.width, MoveID.RightOrUp, canvasGroup, false);
            break;

        case "BackFromScanResultBtn":
        case "BluetoothAdvertisingStopBtn":
            bluetoothPeripheralDetailBg.SetActive(false);
            bluetoothConnectWaiting.SetActive(false);
            bluetoothAdvertisingStopBtn.SetActive(false);
            StopScan();
            break;

        case "BluetoothScanBtn":
            StartScan();
            break;

        case "ConnectCancelBtn":
            bluetoothPeripheralDetailBg.SetActive(false);
            break;

        case "BluetoothReScanBtn":
            ReScan();
            break;

        default:
            MyDebug.LogYellow("Can not find Button: " + btn.name);
            break;
        }
    }
Exemplo n.º 10
0
 //deinitialize the bluetooth system when the script is destroyed
 private void OnDestroy()
 {
     if (_connectedAddress != null)
     {//disconnect from a connected device if there is any
         BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null);
         _connectedAddress = null;
         _connected        = false;
         _connecting       = false;
     }
     BluetoothLEHardwareInterface.DeInitialize(null);
 }
Exemplo n.º 11
0
    public void OnBack()
    {
        RemovePeripherals();

        if (_scanning)
        {
            OnScan();              // this will stop scanning
        }
        BluetoothLEHardwareInterface.DeInitialize(() => {
            BLETestScript.Show(PanelTypeSelection);
        });
    }
Exemplo n.º 12
0
    private void OnDestroy()
    {
        BluetoothLEHardwareInterface.DeInitialize(null);

        BluetoothLE.connecting       = false;
        BluetoothLE.connectDataState = false;
        BluetoothLE.connectState     = false;
        if (this.debugOutput)
        {
            Debug.Log("BluetoothLE.OnDestroy called");
        }
    }
Exemplo n.º 13
0
    IEnumerator disConnectProcess()
    {
        BluetoothLEHardwareInterface.StopScan();
        yield return(new WaitForSeconds(0.2f));

        BluetoothLEHardwareInterface.DisconnectAll();
        yield return(new WaitForSeconds(0.2f));

        BluetoothLEHardwareInterface.DeInitialize(() => {
            SetState(BtStates.None);
        });
    }
 void disconnectToDevice()
 {
     if (_connected)
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(_JDY16, (address) => {
             BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; });
         });
     }
     else
     {
         BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; });
     }
 }
Exemplo n.º 15
0
 void StartProcess()
 {
     Alert.Show("Bluetooth initialization will fail if Bluetooth settings are not initialized", null, false);
     BluetoothLEHardwareInterface.Initialize(true, false, () => {
         SetState(States.Scan, 0.2f);
     }, (error) => {
         // Console.Write ("蓝牙初始化失败: " + error + ",等待重试");
         Alert.Show("Initialize Faild, Please open the Bluetooth", (_value) => {
             BluetoothLEHardwareInterface.DeInitialize(null);
             SetState(States.Init, 0.2f);
         });
     });
 }
Exemplo n.º 16
0
    void InitBluetooth(DeviceName[] _supportedDevices)
    {
        Debug.Log("Bluetooth Initializing...");
        BluetoothDeviceScript receiver = BluetoothLEHardwareInterface.Initialize(true, false, () =>
        {
            Debug.Log("Bluetooth Initialized.");
            Scan(_supportedDevices);
        }, (err) =>
        {
            Debug.Log("Bluetooth Error: " + err);
            if ("Bluetooth LE Not Enabled" == err)
            {
                BluetoothLEHardwareInterface.FinishDeInitialize();
                BluetoothLEHardwareInterface.DeInitialize(() => { StartCoroutine(ReInitBluetooth(_supportedDevices)); });
            }
        });

        DontDestroyOnLoad(receiver.gameObject);
    }
Exemplo n.º 17
0
    private void ConnectDevice(string addr)
    {
        BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) =>
        {
        },
                                                         (address, serviceUUID) =>
        {
        },
                                                         (address, serviceUUID, characteristicUUID) =>
        {
            if (IsEqual(serviceUUID, _serviceUUID))
            {
                _connectedID = address;
                isConnected  = true;

                if (IsEqual(characteristicUUID, _readCharacteristicUUID))
                {
                    _readFound = true;
                }
                if (IsEqual(characteristicUUID, _writeCharacteristicUUID))
                {
                    _writeFound = true;
                }
                adressFinal = addr;
                Debug.Log("BLE Spiro Connected");
                BluetoothLEHardwareInterface.StopScan();
            }
        }, (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
            Debug.Log("Connection Lost");
            isConnected = false;
            //we first need to disconnect and deinitialize before we can connect again to the Air next otherwise we can't reconnect.
            BluetoothLEHardwareInterface.DisconnectAll();
            BluetoothLEHardwareInterface.DeInitialize(() => { });
            BluetoothLEHardwareInterface.FinishDeInitialize();
            DeviceManager.Instance.MakeSpiroControllerNull();
        });
    }
Exemplo n.º 18
0
    void SetMode(eMode Mode)
    {
        DebugLog("BLEMgr:" + Mode.ToString());
        m_Mode      = Mode;
        m_ModeTimer = 0;

        switch (m_Mode)
        {
        case eMode.ScanDevice: ExecScanDevice(); break;

        case eMode.Connect: ExecConnect(); break;

        case eMode.ConnectOK:
            if (m_ScanAndConnectSuccess != null)
            {
                m_ScanAndConnectSuccess();
            }
            m_ScanAndConnectSuccess = null;
            m_ScanAndConnectError   = null;
            m_StatusChangedCallback(Hot2gEnumerations.EnumHot2gDriverCommStsEvent.Connected, m_DeviceAddress);
            break;

        case eMode.Error:
            BluetoothLEHardwareInterface.StopScan();

            BluetoothLEHardwareInterface.DeInitialize(() =>
            {
                if (m_ScanAndConnectError != null)
                {
                    m_ScanAndConnectError();
                }
            });
            break;

        case eMode.DisConnect:
            BluetoothLEHardwareInterface.DeInitialize(() =>
            {
                m_StatusChangedCallback(Hot2gEnumerations.EnumHot2gDriverCommStsEvent.Disconnected, m_DeviceAddress);
            });
            break;
        }
    }
Exemplo n.º 19
0
    private void OnDestroy()
    {
        Debug.Log("BluetoothManager - OnDestroy()");

        if (Instance == this)
        {
            try
            {
                BluetoothLEHardwareInterface.StopScan();
                BluetoothLEHardwareInterface.DisconnectAll();
                BluetoothLEHardwareInterface.DeInitialize(() => {
                    Debug.Log("Bluetooth has shut down on destroy.");
                });
            }
            catch (Exception e)
            {
                Debug.Log("Bluetooth has already shut down: " + e.Message);
            }
        }
    }
Exemplo n.º 20
0
 void ForceDisconnect()
 {
     if (_connected)
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
             BluetoothLEHardwareInterface.DeInitialize(() => {
                 is_quit_ok = true;
                 _connected = false;
                 _state     = States.None;
             });
         });
     }
     else
     {
         BluetoothLEHardwareInterface.DeInitialize(() => {
             _state     = States.None;
             is_quit_ok = true;
         });
     }
     Reset();
 }
Exemplo n.º 21
0
    public void OnBluetoothFightFinish()
    {
        MyDebug.LogGreen("OnBluetoothFightFinish");
        if (isCentral)
        {
            MyDebug.LogGreen("OnBluetoothFightFinish:Central");
            BluetoothLEHardwareInterface.UnSubscribeCharacteristic(CurPeripheralInstance.address,
                                                                   ServiceUUID,
                                                                   ReadUUID,
                                                                   (characteristic) =>
            {
                MyDebug.LogGreen("UnSubscribeCharacteristic Success :" + characteristic);
            });

            BluetoothLEHardwareInterface.DisconnectPeripheral(CurPeripheralInstance.address,
                                                              (disconnectAddress) =>
            {
                MyDebug.LogGreen("DisconnectPeripheral Success:" + disconnectAddress);
            });
        }
        else
        {
            MyDebug.LogGreen("OnBluetoothFightFinish:Peripheral");
            BluetoothLEHardwareInterface.StopAdvertising(() =>
            {
                MyDebug.LogGreen("Stop Advertising!");
            });
        }

        BluetoothLEHardwareInterface.RemoveCharacteristics();
        BluetoothLEHardwareInterface.RemoveServices();

        BluetoothLEHardwareInterface.DeInitialize(() =>
        {
            MyDebug.LogGreen("DeInitialize Success!");
        });
        BluetoothLEHardwareInterface.BluetoothEnable(false);
    }
Exemplo n.º 22
0
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;

            if (_timeout <= 0f)
            {
                _timeout = 0f;

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

                case machineState.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
                        Debug.Log("Found Device : " + address + " / Name : " + name);

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

                            state       = State.DeviceFound;
                            device_name = name;

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

                case machineState.Connect:
                    // set these flags
                    _foundAccel = false;
                    _foundGyro  = false;
                    _foundTouch = 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, foundServiceUUID, foundCharUUID) => {
                        if (IsEqual(foundServiceUUID, ServiceUUID))
                        {
                            _foundAccel = _foundAccel || IsEqual(foundCharUUID, AccelUUID);
                            _foundGyro  = _foundGyro || IsEqual(foundCharUUID, GyroUUID);
                            _foundTouch = _foundTouch || IsEqual(foundCharUUID, TouchUUID);

                            // if we have found all 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 (_foundAccel && _foundGyro && _foundTouch)
                            {
                                Debug.Log("Connected");
                                state = State.Connected;
                                SetState(machineState.Subscribe, 3f);
                            }
                        }
                    });
                    break;

                case machineState.Subscribe:
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(TouchUUID), null, onNotification);
                    System.Threading.Thread.Sleep(500);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(AccelUUID), null, onNotification);
                    System.Threading.Thread.Sleep(500);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(GyroUUID), null, onNotification);
                    break;

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

                case machineState.Disconnect:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = machineState.None;
                        });
                    });
                    break;
                }
            }
        }
    }
Exemplo n.º 23
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:
                    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 (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
                    });
                    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, SubscribeCharacteristic);
                            _foundWriteID     = _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 (_foundSubscribeID && _foundWriteID)
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);
                            }
                        }
                    });
                    break;

                case States.Subscribe:
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, 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;
                    });
                    break;

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

                case States.Disconnect:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                        BluetoothLEHardwareInterface.Log("1");
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _connected = false;
                            _state     = States.None;
                        });
                    });
                    break;
                }
            }
        }
    }
Exemplo n.º 24
0
    void Update()
    {
        RotatePlayer();
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;
                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    HM10_Status.text = "Scanning for HM10 devices...";
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                        if (name.Contains(DeviceName))
                        {
                            _workingFoundDevice = true;
                            BluetoothLEHardwareInterface.StopScan(); // stop scanning while you connect to a device
                            _hm10            = address;              // add it to the list and set to connect to it
                            HM10_Status.text = "Found HM10";
                            SetState(States.Connect, 0.5f);
                            _workingFoundDevice = false;
                        }
                    }, null, false, false);
                    break;

                case States.Connect:
                    HM10_Status.text = "Connecting to HM10";
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_hm10, null, null, (address, serviceUUID, characteristicUUID) => {
                        if (IsEqual(serviceUUID, ServiceUUID))
                        {
                            if (IsEqual(characteristicUUID, Characteristic))
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);
                            }
                        }
                    }, (disconnectedAddress) => {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        HM10_Status.text = "Disconnected";
                    });
                    break;

                case States.Subscribe:
                    HM10_Status.text = "Connected to HM10";
                    enabled          = true;
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) => {});
                    _state = States.None;    // set to the none state and the user can start sending and receiving data

                    break;

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

                case States.Disconnect:
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_hm10, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                        enabled = false;
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 25
0
    /// <summary>
    /// Update
    /// </summary>
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout > 0f)
            {
                return;
            }

            _timeout = 0f;


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

            //Scan
            case States.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
                    // デバイスがrssiおよびメーカー固有のデータをアドバタイズしない場合、次のコールバックはメーカー固有のデータがある場合にのみ呼び出されるため、このコールバックを使用する必要があります。

                    _deviceName += string.Format(",{0} ", name);

                    if (!_rssiOnly)
                    {
                        if (name.Contains(DeviceName))
                        {
                            _deviceName += string.Format("[FIND]-{0}\n", _deviceAddress);

                            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);
                        }
                        else
                        {
                            _deviceName += "\n";
                        }
                    }

                    if (LogText != null)
                    {
                        LogText.text = _deviceName;
                    }
                }, (address, name, rssi, bytes) =>
                {
                    // use this one if the device responses with manufacturer specific data and the rssi
                    // デバイスがメーカー固有のデータと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;

            //ScanRSSI
            case States.ScanRSSI:
                break;

            //Connect
            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.
                // 最初のパラメータは名前ではなくアドレスであることに注意してください。後方互換性のため、これは修正していません。
                // また、最初の2つのコールバックを使用していることに注意してください。特定の特性を探していない場合は、最初の2つのいずれかを使用できますが、
                // デバイスはすべてを列挙するので、サブスクライブする前に列挙が完了するまでタイムアウトを大きくする必要があることに注意してください。他の操作を行います。

                BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) =>
                {
                    _serviceName += string.Format("{0} ", serviceUUID);


                    if (IsEqual(serviceUUID, ServiceUUID))
                    {
                        _serviceName += string.Format("[FIND]-{0}\n", _deviceAddress);

                        _foundSubscribeID = _foundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic);
                        _foundWriteID     = _foundWriteID || IsEqual(characteristicUUID, WriteCharacteristic);


                        _serviceName += string.Format("<{0}>,{1},{2}\n", characteristicUUID, _foundSubscribeID, _foundWriteID);


                        // 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 && _foundWriteID)
                        if (_foundSubscribeID)
                        {
                            _connected = true;
                            SetState(States.Subscribe, 2f);
                        }
                    }
                    else
                    {
                        _serviceName += "\n";
                    }

                    if (Log2Text != null)
                    {
                        Log2Text.text = _serviceName;
                    }
                });
                break;

            // Subscribe
            case States.Subscribe:
                BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, 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.
                    // 実際にデータが返されるまで待つ以外に、状態を設定する優れた方法はありません。このrfduinoのデモでは、GUIが更新される前にrfduinoのボタンを少なくとも1回押すことを意味します。
                    _state = States.None;

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

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

            // Disconnect
            case States.Disconnect:
                if (_connected)
                {
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) =>
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() =>
                        {
                            _connected = false;
                            _state     = States.None;
                        });
                    });
                }
                else
                {
                    BluetoothLEHardwareInterface.DeInitialize(() =>
                    {
                        _state = States.None;
                    });
                }
                break;
            }
        }
    }
Exemplo n.º 26
0
 public void OnButton()
 {
     BluetoothLEHardwareInterface.DeInitialize(() => Debug.Log("Deinitialized"));
 }
Exemplo n.º 27
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;
                }
            }
        }
    }
 void OnApplicationQuit()
 {
     BluetoothLEHardwareInterface.DeInitialize(null);
 }
Exemplo n.º 29
0
    void Bluetooth_Baglan()
    {
        if (Bluetooth_Bilgileri.State_Timeout > 0f)
        {
            Bluetooth_Bilgileri.State_Timeout -= Time.deltaTime;
            if (Bluetooth_Bilgileri.State_Timeout <= 0f)
            {
                Bluetooth_Bilgileri.State_Timeout = 0f;

                switch (Bluetooth_Bilgileri.State)
                {
                case Bluetooth_States.None:
                    break;

                case Bluetooth_States.Scan:

                    Status_Update(Bluetooth_DeviceName + " aranıyor...");

                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                        // we only want to look at devices that have the name we are looking for
                        // this is the best way to filter out devices
                        if (name.Contains(Bluetooth_DeviceName))
                        {
                            // it is always a good idea to stop scanning while you connect to a device
                            // and get things set up
                            BluetoothLEHardwareInterface.StopScan();
                            Status_Update(Bluetooth_DeviceName + " bulundu...");

                            // add it to the list and set to connect to it
                            Bluetooth_Bilgileri.Device_Address = address;

                            SetState(Bluetooth_States.Connect, 0.5f);
                        }
                    }, null, false, false);
                    break;

                case Bluetooth_States.Connect:
                    // set these flags

                    Status_Update(Bluetooth_DeviceName + " cihazına bağlanılıyor...");

                    // 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(Bluetooth_Bilgileri.Device_Address, null, null, (address, serviceUUID, characteristicUUID) => {
                        if (UUIDIsEqual(serviceUUID, Bluetooth_ServiceUUID))
                        {
                            // if we have found the characteristic 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 (UUIDIsEqual(characteristicUUID, Bluetooth_Characteristic))
                            {
                                Bluetooth_Bilgileri.Connected = true;
                                SetState(Bluetooth_States.Subscribe, 2f);

                                Status_Update(Bluetooth_DeviceName + " cihazına bağlanıldı.");
                            }
                        }
                    }, (disconnectedAddress) => {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        Status_Update(Bluetooth_DeviceName + " cihazı ile bağlantı kesildi!");
                    });
                    break;

                case Bluetooth_States.Subscribe:
                    Status_Update("Veri alımına kaydolunuyor...");

                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(Bluetooth_Bilgileri.Device_Address, Bluetooth_ServiceUUID, Bluetooth_Characteristic, null, (address, characteristicUUID, bytes) => {
                        Bluetooth_Bilgileri.Receive_Count++;
                        BluetoothLEHardwareInterface.Log("Alinan: " + Encoding.UTF8.GetString(bytes));
                        Status_Update("Alınan veri: " + Encoding.UTF8.GetString(bytes));

                        Bluetooth_Verilerini_Isle(bytes);
                    });

                    // set to the none state and the user can start sending and receiving data
                    SetState(Bluetooth_States.None, 0);
                    Status_Update("Veri bekleniyor...");

                    break;

                case Bluetooth_States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(Bluetooth_Bilgileri.Device_Address, Bluetooth_ServiceUUID, Bluetooth_Characteristic, null);
                    SetState(Bluetooth_States.Disconnect, 4f);
                    break;

                case Bluetooth_States.Disconnect:
                    if (Bluetooth_Bilgileri.Connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(Bluetooth_Bilgileri.Device_Address, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                Bluetooth_Bilgileri.Connected = false;
                                SetState(Bluetooth_States.None, 0);
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            SetState(Bluetooth_States.None, 0);
                        });
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 30
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:
                    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;
                }
            }
        }
    }