Exemplo n.º 1
0
        /// <summary>
        /// Unregister from a given characteristic
        /// </summary>
        public static void Unsubscribe(Characteristic characteristic)
        {
            CheckIfInitialized();

            BluetoothLEHardwareInterface.UnSubscribeCharacteristic(characteristic.Device.Address,
                                                                   characteristic.ServiceUuid, characteristic.CharacteristicUuid, null);
        }
Exemplo n.º 2
0
    void ExecConnect()
    {
        DebugLog("ConnectAddress:" + m_DeviceAddress);

        BluetoothLEHardwareInterface.ConnectToPeripheral(m_DeviceAddress, null, null,
                                                         // 接続に成功した時の挙動
                                                         (address, serviceUUID, characteristicUUID) =>
        {
            DebugLog("Address:" + address + ", serviceUUID:" + serviceUUID + ", characteristicUUID:" + characteristicUUID);

            m_ConnectCharacteristicUUID[characteristicUUID.ToLower()] = true;

            for (int i = 0; i < CharacteristicUUID.Length; i++)
            {
                if (m_ConnectCharacteristicUUID[CharacteristicUUID[i].ToLower()] == false)
                {
                    return;
                }
            }

            ReceiveNotification();

            SetMode(eMode.ConnectOK);
        },
                                                         // 切断コールバック
                                                         (disconnectedAddress) =>
        {
            if (disconnectedAddress == m_DeviceAddress)
            {
                SetMode(eMode.DisConnect);
            }
        });
    }
Exemplo n.º 3
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.º 4
0
 void sendBytesBluetooth(byte[] data)
 {
     BluetoothLEHardwareInterface.Log(string.Format("data length: {0} data {1} uuid: {2}", data.Length.ToString(), ASCIIEncoding.UTF8.GetString(data), _writeCharacteristicUUID));
     BluetoothLEHardwareInterface.WriteCharacteristic(_connectedID, _serviceUUID, _writeCharacteristicUUID, data, data.Length, false, (characteristicUUID) => {
         BluetoothLEHardwareInterface.Log("Write Succeeded");
     });
 }
Exemplo n.º 5
0
    void AddPeripheral(string name, string address)
    {
        txtDebug.text += ("Found " + name + " \r\n");

        if (_peripheralList == null)
        {
            _peripheralList = new Dictionary <string, string>();
        }
        if (!_peripheralList.ContainsKey(address))
        {
            _peripheralList[address] = name;
            if (name.Trim().ToLower() == deviceToConnectTo.Trim().ToLower())
            {
                txtDebug.text += "Found our device, stop scanning \n";
                BluetoothLEHardwareInterface.StopScan();

                txtDebug.text += "Connecting to " + address + "\n";
                connectBluetooth(address);
            }
            else
            {
                txtDebug.text += "Not what we're looking for \n";
            }
        }
        else
        {
            txtDebug.text += "No address found \n";
        }
    }
Exemplo n.º 6
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";
     });
 }
Exemplo n.º 7
0
 private void WriteCharacteristic(byte[] data)
 {
     BluetoothLEHardwareInterface.WriteCharacteristic(deviceAddress, ServiceUUID, RXUUID, data.ToArray(), data.Length, true, (characteristicUUID) =>
     {
         BluetoothLEHardwareInterface.Log("Write Succeeded with characteristic: " + characteristicUUID);
     });
 }
Exemplo n.º 8
0
 private void setServoPos(bool queue)
 {
     byte[] numArray = new byte[] { 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 };
     for (int i = 0; i < 8; i++)
     {
         byte[] numArray1 = this.actualPos;
         byte   num       = this.adjust(this.actualPos[i], this.targetPos[i]);
         byte   num1      = num;
         numArray1[i]    = num;
         numArray[i + 1] = num1;
     }
     this.calculateChecksum(ref numArray);
     if (BluetoothLE.connectState && BluetoothLE.writeState)
     {
         if (queue)
         {
             this.commandQueue.Add(numArray);
         }
         else
         {
             BluetoothLEHardwareInterface.WriteCharacteristic(this.uuids[this.connectedDevice], this.serviceUUID, this.characteristicUUID, numArray, 20, this.ack, new Action <string>(this.setResult));
         }
         StringBuilder stringBuilder = new StringBuilder();
         for (int j = 1; j <= 8; j++)
         {
             stringBuilder.Append(string.Concat(numArray[j].ToString("X2"), " "));
         }
         if (this.debugOutput)
         {
             Debug.Log(string.Concat(new object[] { "*** setServoPos: ", stringBuilder.ToString(), " (", Time.realtimeSinceStartup, ")" }));
         }
     }
 }
Exemplo n.º 9
0
 private void Awake()
 {
     if (this.debugOutput)
     {
         Debug.Log("BluetoothLE.Awake called");
     }
     if (BluetoothLE.created)
     {
         UnityEngine.Object.Destroy(base.gameObject);
     }
     else
     {
         UnityEngine.Object.DontDestroyOnLoad(this);
         BluetoothLE.bluetoothDeviceScript = BluetoothLEHardwareInterface.Initialize(true, false, new Action(this.Initialized), new Action <string>(this.Error));
         if (null != BluetoothLE.bluetoothDeviceScript)
         {
             UnityEngine.Object.DontDestroyOnLoad(BluetoothLE.bluetoothDeviceScript);
             BluetoothLE.bluetoothDeviceScript.DisconnectedPeripheralAction = new Action <string>(this.disconnectedPeripheralAction);
         }
         BluetoothLE.created = true;
         if (this.debugOutput)
         {
             Debug.Log("BluetoothLE.Awake initialized");
         }
         BluetoothLE.instance = this;
     }
     Array.Clear(this.status, 0, (int)this.status.Length);
     Array.Clear(this.config, 0, (int)this.config.Length);
     Array.Clear(this.mapping, 0, (int)this.mapping.Length);
 }
Exemplo n.º 10
0
    void OnGUI()
    {
        GUI.skin.textArea.fontSize = 32;
        GUI.skin.button.fontSize   = 32;
        GUI.skin.toggle.fontSize   = 32;
        GUI.skin.label.fontSize    = 32;

        if (_connected)
        {
            if (_state == States.None)
            {
                if (GUI.Button(new Rect(10, 10, Screen.width - 10, 100), "Disconnect"))
                {
                    SetState(States.Unsubscribe, 1f);
                }

                if (GUI.Button(new Rect(10, 210, Screen.width - 10, 100), "Write Value"))
                {
                    OnLED();
                }

                if (_dataBytes != null)
                {
                    string data = "";
                    foreach (var b in _dataBytes)
                    {
                        data += b.ToString("X") + " ";
                    }

                    GUI.TextArea(new Rect(10, 400, Screen.width - 10, 300), data);
                }
            }
            else if (_state == States.Subscribe && _timeout == 0f)
            {
                GUI.TextArea(new Rect(50, 100, Screen.width - 100, Screen.height - 200), "Press the button on the RFduino");
            }
        }
        else if (_state == States.ScanRSSI)
        {
            if (GUI.Button(new Rect(10, 10, Screen.width - 10, 100), "Stop Scanning"))
            {
                BluetoothLEHardwareInterface.StopScan();
                SetState(States.Disconnect, 0.5f);
            }

            if (_rssi != 0)
            {
                GUI.Label(new Rect(10, 300, Screen.width - 10, 50), string.Format("RSSI: {0}", _rssi));
            }
        }
        else if (_state == States.None)
        {
            if (GUI.Button(new Rect(10, 10, Screen.width - 10, 100), "Connect"))
            {
                StartProcess();
            }

            _rssiOnly = GUI.Toggle(new Rect(10, 200, Screen.width - 10, 50), _rssiOnly, "Just Show RSSI");
        }
    }
Exemplo n.º 11
0
    IEnumerator SubscribeSensor3()
    {
        connectedAmount++;
        Debug.Log("Connected amount is:" + connectedAmount);
        Sup.text = "Subscribing to sensor 3...";
        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(Address3, _serviceUUID, _characteristicUUID, (deviceAddress, notification) =>
        {
        }, (deviceAddress2, characteristic, data) =>
        {
            seonsor2msgArrayData = data;
            Sensor2DataToTransformArm(seonsor2msgArrayData);

            /*
             * isSensor3Subscribed = true;
             * Sup.text = "Subscribed to sensor 3.";
             * statusImageSensor2.texture = greenLight;
             *
             * limbAngle3 = handleMessage_Premius2(data);
             * ShoulderL.transform.eulerAngles = new Vector3(0, 0, (270+limbAngle3));        //Insert the handled data to a joint (only Z-axis)
             *
             * // Save highest ROM during game play
             * if ((limbAngle3 > GameControl.instance.maxRomAchievedRight) && (GameControl.instance.workoutTimer > 0.0f))
             * {
             *  GameControl.instance.maxRomAchievedRight = limbAngle3;
             * }
             */
        });
        yield return(null);
    }
Exemplo n.º 12
0
    void StartScan()
    {
        EventDispatcher.SendEvent(eBT_CONNECTION_STATUS, "Ищем устройство.");

        int tryCount = 0;

        BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null,
                                                                    (address, deviceName, rssi, bytes) => {
            tryCount++;
            if (deviceName.Contains(DeviceName))
            {
                BluetoothLEHardwareInterface.StopScan();

                deviceAddress = address;
                SetState(BtStates.Connect, 0.5f);
            }
            else if (tryCount == 20)
            {
                EventDispatcher.SendEvent(eBT_CONNECTION_STATUS, "Ищем устройство. \n Возможно контроллер зеркал отключил свой модуль bluetoth по истечению таймера — выключите и включите зажигание.");
            }
            else if (tryCount > 50)
            {
                BluetoothLEHardwareInterface.StopScan();
                Debug.Log("Scan failed. Service Does not found");

                SetState(BtStates.ConnectingError, 0.3f);
            }
        }, false);
    }
Exemplo n.º 13
0
        /// <summary>
        /// Connects to a device and gets its characteristic items. You can check if that device has the services +
        /// characteristics that you are looking for. An error may happen on the way, so check the error callback
        /// </summary>
        public static void ConnectToDevice(Device device, OnCharacteristicFound onCharacteristicFound, Action <string> onDisconnect)
        {
            CheckIfInitialized();

            if (CurrentState != State.Scanning && CurrentState != State.Disconnected)
            {
                throw new Exception("You can only connect to a device after you have scanned for devices. Maybe it's not " +
                                    "true though :)");
            }

            SetState(State.Connecting);
            Observable
            .Timer(TimeSpan.FromSeconds(0.5f))
            .Subscribe(_ =>
            {
                BluetoothLEHardwareInterface.ConnectToPeripheral(device.Address, null, null,
                                                                 (address, serviceUuid, characteristicUuid) =>
                {
                    SetState(State.Connected);
                    onCharacteristicFound?.Invoke(new Characteristic
                    {
                        Device             = device,
                        ServiceUuid        = serviceUuid,
                        CharacteristicUuid = characteristicUuid
                    });
                },
                                                                 disconnectedAddress =>
                {
                    SetState(State.Disconnected);
                    BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                    onDisconnect?.Invoke(disconnectedAddress);
                });
            });
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes the BLE service and returns it's result via callbacks. If successful, you can start scanning
        /// for devices
        /// </summary>
        public static void Initialize(Action onSuccess, Action <string> onError, bool asCentral = true,
                                      bool asPeripheral = false)
        {
            if (IsInitialized)
            {
                Debug.LogError("BLE Service is already initialized");
                return;
            }

            IsInitialized = true;

            BluetoothLEHardwareInterface.Initialize(asCentral, asPeripheral,
                                                    () =>
            {
                IsInitialized = true;
                SetState(State.ReadyToScan);
                onSuccess?.Invoke();
            },
                                                    error =>
            {
                BluetoothLEHardwareInterface.Log("Error: " + error);
                onError?.Invoke(error);
            });

            Observable
            .OnceApplicationQuit()
            .Subscribe(unit => { DeInitialize(); });
        }
Exemplo n.º 15
0
    //Receive Euler
    public static double[] ReceiveEuler()
    {
        double[] euler = new double[3];

        Debug.Log("ENTROU NO RECEBER Euler");
        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(bsnDevice.Address, FullBSNUUID(_serviceReadUUID), FullBSNUUID(_readEulerUUID), (deviceAddress, notification) =>
        {
        }, (deviceAddress2, characteristic, data) =>
        {
            //Receive ROLL data
            byte[] dataRoll = { data[0], data[1], data[2], data[3] };
            euler[0]        = System.BitConverter.ToInt32(dataRoll, 0) / 65536.0; // 44100.0
            //Debug.Log("Roll = " + euler[0]);

            //Receive PITCH data
            byte[] dataPitch = { data[4], data[5], data[6], data[7] };
            euler[1]         = System.BitConverter.ToInt32(dataPitch, 0) / 65536.0; // 44100.0
            //Debug.Log("Pitch = " + euler[1]);

            //Receive YAW data
            byte[] datayaw = { data[8], data[9], data[10], data[11] };
            euler[2]       = System.BitConverter.ToInt32(datayaw, 0) / 65536.0; // 44100.0
            //Debug.Log("Yaw = " + euler[2]);

            // Debug.Log("ENVIOU BYTES : " + data);
            // Debug.Log("ENVIOU BYTES STRING : " + Encoding.ASCII.GetString(data));
            // Debug.Log("ENVIOU BYTES STRING : " + Encoding.Default.GetString(data));
            // Debug.Log("ENVIOU BYTES Lenght : " + data.Length);
        });
        Debug.Log("DEPOIS DO READ");
        return(euler);
    }
Exemplo n.º 16
0
 private void SendCommand(byte[] ch1, bool queue)
 {
     if (!BluetoothLE.connectState)
     {
         return;
     }
     this.calculateChecksum(ref ch1);
     if (this.debugOutput)
     {
         string empty    = string.Empty;
         byte[] numArray = ch1;
         for (int i = 0; i < (int)numArray.Length; i++)
         {
             byte num = numArray[i];
             empty = string.Concat(empty, string.Format("{0:X2}", num));
         }
     }
     if (queue)
     {
         this.commandQueue.Add(ch1);
     }
     else
     {
         BluetoothLEHardwareInterface.WriteCharacteristic(this.uuids[this.connectedDevice], this.serviceUUID, this.characteristicUUID, ch1, 20, this.ack, new Action <string>(this.Result));
         Debug.Log("*** Debug: Send command!");
         if (ch1[0] == 11)
         {
             BluetoothLE.writeState = (ch1[1] == 0 ? true : ch1[1] == 2);
         }
     }
 }
Exemplo n.º 17
0
    //Receive Gravity Vector
    public static double[] ReceiveGravityVector()
    {
        double[] gravityVector = new double[3];
        Debug.Log("ENTROU NO RECEBER gravidade vetor");
        Debug.Log("NOME = " + bsnDevice.Name);
        Debug.Log("ADRESS = " + bsnDevice.Address);
        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(bsnDevice.Address, FullBSNUUID(_serviceReadUUID), FullBSNUUID(_readGravityVectorUUID), (deviceAddress, notification) =>
        {
        }, (deviceAddress2, characteristic, data) =>
        {
            //Receive X-AXYS data
            byte[] dataX     = { data[0], data[1], data[2], data[3] };
            gravityVector[0] = System.BitConverter.ToSingle(dataX, 0);
            //Debug.Log("X = " + gravityVector[0]);

            //Receive Y-AXYS data
            byte[] dataY     = { data[4], data[5], data[6], data[7] };
            gravityVector[1] = System.BitConverter.ToSingle(dataY, 0);
            //Debug.Log("Y = " + gravityVector[1]);

            //Receive Z-AXYS data
            byte[] dataZ     = { data[8], data[9], data[10], data[11] };
            gravityVector[2] = System.BitConverter.ToSingle(dataZ, 0);
            //Debug.Log("Z = " + gravityVector[2]);

            // Debug.Log("ENVIOU BYTES : " + data);
            // Debug.Log("ENVIOU BYTES STRING : " + Encoding.ASCII.GetString(data));
            // Debug.Log("ENVIOU BYTES STRING : " + Encoding.Default.GetString(data));
            // Debug.Log("ENVIOU BYTES Lenght : " + data.Length);
        });
        Debug.Log("DEPOIS DO READ");
        return(gravityVector);
    }
Exemplo n.º 18
0
    private IEnumerator SendArduino()
    {
        yield return(new WaitForSeconds(1.0f));  //wait awhile before playing song

        WaitForSeconds wait = new WaitForSeconds(0.5f);

        string[] lines = d.TextFile.text.Split('\n');
        foreach (string line in lines)
        {
            if (!string.IsNullOrWhiteSpace(line))     // beat contains notes
            {
                print(line);
                foreach (string note in Regex.Split(line, " "))
                {
                    int key = int.Parse(note);
                    print("sending " + key + ": " + dict[key]);
                    // stream.Write(dict[key]);
                    var data = Encoding.UTF8.GetBytes(dict[key]);
                    BluetoothLEHardwareInterface.WriteCharacteristic(_hm10, ServiceUUID, Characteristic, data, data.Length, false, (characteristicUUID) => {
                        BluetoothLEHardwareInterface.Log("Write Succeeded");
                    });
                }
            }
            yield return(wait); //tempo of song
        }
        StartCoroutine(ReturnPlayer(1.0f));
    }
Exemplo n.º 19
0
    private void ConnectToTargetDevice()
    {
        BluetoothLEHardwareInterface.Log("Connecting to " + DeviceName);
        foundTXUUID = false;
        foundRXUUID = false;

        BluetoothLEHardwareInterface.ConnectToPeripheral(deviceAddress, null, null,
                                                         (address, serviceUUID, characteristicUUID) => {
            if (IsEqual(serviceUUID, ServiceUUID))
            {
                BluetoothLEHardwareInterface.Log("Connected to Puck UUID: " + serviceUUID);
                foundTXUUID = foundTXUUID || IsEqual(characteristicUUID, TXUUID);
                foundRXUUID = foundRXUUID || IsEqual(characteristicUUID, RXUUID);

                // Make sure there is enough timeout that if the device is still enumerating other characteristics
                // it finishes before we try to subscribe
                if (foundTXUUID && foundRXUUID)
                {
                    SetState(States.Subscribe, 2f);
                }
            }
        },
                                                         (err) =>
        {
            connected = false;
            SetState(States.Connect, 0.5f);
        }
                                                         );
    }
Exemplo n.º 20
0
    void Start()
    {
        Debug.Log("Bluetooth Initializing...");
        BluetoothDeviceScript receiver = BluetoothLEHardwareInterface.Initialize(true, false, () =>
        {
            Debug.Log("Bluetooth Initialized.");
            Debug.Log("Start scanning...");
            BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null, (deviceID, name, rssi, adInfo) =>
            {
                //  deviceID:   安卓上是 MAC 地址,iOS 上是某一串不明代码
                //  adInfo:     广播数据,第 2-7 字节是 MAC 地址
                if (("R-ARCHER" == name) || ("GU-ARCHER" == name))
                {
                    Debug.Log("Found: " + name);
                    //BluetoothLEHardwareInterface.StopScan();

                    GeekplayDevice device = GetDeviceScript(name);
                    device.SetAppInfo("", "", "", "");
                    device.m_deviceID = deviceID;
                    device.m_MAC      = deviceID.Replace(":", "");

                    deviceList.Add(device);
                    if (typeof(GeekplayHunter) == device.GetType())
                    {
                        ((GeekplayHunter)device).Initialize(BowDraw, BowShoot);
                    }
                    else if (typeof(GeekplayDragonbone) == device.GetType())
                    {
                        ((GeekplayDragonbone)device).Initialize(BowDraw, BowShoot);
                    }
                }
            });
        }, null);
    }
Exemplo n.º 21
0
 public void DeinitializeBluetooth()
 {
     BluetoothLEHardwareInterface.DeInitialize(() =>
     {
         Debug.Log("Bluetooth has shut down.");
     });
 }
Exemplo n.º 22
0
    public static void DeInitialize(Action action)
    {
        if (bluetoothDeviceScript != null)
        {
            bluetoothDeviceScript.DeinitializedAction = action;
        }

#if EXPERIMENTAL_MACOS_EDITOR && (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX)
        BluetoothLEHardwareInterface.OSXBluetoothLEDeInitialize();
#else
        if (Application.isEditor)
        {
            if (bluetoothDeviceScript != null)
            {
                bluetoothDeviceScript.SendMessage("OnBluetoothMessage", "DeInitialized");
            }
        }
        else
        {
#if UNITY_IOS || UNITY_TVOS
            _iOSBluetoothLEDeInitialize();
#elif UNITY_ANDROID
            if (_android != null)
            {
                _android.Call("androidBluetoothDeInitialize");
            }
#endif
        }
#endif
    }
Exemplo n.º 23
0
    void connectBluetooth(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;
                }

                BluetoothLEHardwareInterface.Log("Characteristic found: " + address + " -> " + serviceUUID + " -> " + characteristicUUID + "\n");
            }
        }, (address) => {
            isConnected = false;
        });

        _connecting = false;
    }
 private void DisconnectFromDevice()
 {
     BluetoothLEHardwareInterface.DisconnectPeripheral(DeviceAddress, (address) =>
     {
         SetState(States.Disconnected, 0.1f);
     });
 }
Exemplo n.º 25
0
 void SendByte(byte value)
 {
     byte[] data = new byte[] { value };
     BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ServiceUUID, WriteCharacteristic, data, data.Length, true, (characteristicUUID) => {
         BluetoothLEHardwareInterface.Log("Write Succeeded");
     });
 }
    public void OnClick()
    {
        loadingobject = TW.AddLoading(null, 30);
        Debug.Log("TOAN2440: OnClick");
        DICT_OBTAINED.Clear();
        BluetoothLEHardwareInterface.StopScan();

        if (!_is_get_auto)
        {
            Debug.Log("TOAN2440: Calling StartCoroutine after 4 seconds");
            _is_get_auto = true;
            StartCoroutine(GetAllInfor(4f));
        }

        BluetoothLEHardwareInterface.ConnectToPeripheral(address, (connectAction) =>
        {
            Debug.Log("TOAN2441: Connected OK to " + connectAction);
        },
                                                         (serviceAction, serviceActio2) =>
        {
            Debug.Log("TOAN2442: " + serviceAction + " " + serviceActio2);
        }
                                                         , (address, serviceUUID2, characteristicUUID) =>
        {
            Debug.Log("TOAN2444:  " + address + " ; " + serviceUUID2 + " ; " + characteristicUUID);
            if (serviceUUID2.Substring(0, 4).Equals("0000"))
            {
                LISTS.Add(new characteristicUUIDInfo(address, serviceUUID2, characteristicUUID));
            }
        },
                                                         (s1) =>
        {
            Debug.Log("TOAN2445: DISCONNECTED");
        });
    }
Exemplo n.º 27
0
 public void ExecStartSensing()
 {
     byte[] data = createSendMessage(new byte[] { /*0x40, 0x01*/ 0x44, 0x01, 0x02, 0x03, 0x03, 0x07, 0x02, 0x07, 0x02, 0xFF, 0xFF });
     BluetoothLEHardwareInterface.WriteCharacteristic(m_DeviceAddress, ServiceUUID, GENERAL_PURPOSE_CONTROL, data, data.Length, true, (characteristicUUID) => {
         BluetoothLEHardwareInterface.Log("Write Succeeded");
     });
 }
Exemplo n.º 28
0
    public void SendByteR(byte value)
    {
        byte[] data = new byte[] { value };

        BluetoothLEHardwareInterface.WriteCharacteristic(device_right.Address, FullUUID(ServiceUUID), FullUUID(WriteCharacteristic), data, data.Length, true, (characteristicUUID) => {
        });
    }
Exemplo n.º 29
0
    void connectBluetooth(string addr)
    {
        BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => {
        },
                                                         (address, serviceUUID) => {
        },
                                                         (address, serviceUUID, characteristicUUID) => {
            // discovered characteristic
            if (IsEqual(serviceUUID, _serviceUUID))
            {
                _connectedID = address;
                isConnected  = true;

                if (IsEqual(characteristicUUID, _readCharacteristicUUID))
                {
                    _readFound = true;
                }
                if (IsEqual(characteristicUUID, _writeCharacteristicUUID))
                {
                    _writeFound = true;
                }

                txtDebug.text += "Connected";
                BluetoothLEHardwareInterface.StopScan();
                uiPanel.SetActive(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
            isConnected = false;
        });
    }
Exemplo n.º 30
0
        /// <summary>
        /// Subscribe to a given characteristic and sets a delegate where the data will be returned whenever the server
        /// device notifies any new data
        /// </summary>
        public static void Subscribe(Characteristic characteristic, OnDataReceived onDataReceived)
        {
            CheckIfInitialized();

            if (CurrentState != State.Connected && CurrentState != State.Subscribing)
            {
                throw new Exception("You need to be connected to a device before you can subscribe to any characteristic");
            }

            SetState(State.Subscribing);
            Observable
            .Timer(TimeSpan.FromSeconds(2f))
            .Subscribe(_ =>
            {
                Debug.Log("Subscribing..");
                BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Device.Address,
                                                                                      characteristic.ServiceUuid, characteristic.CharacteristicUuid,
                                                                                      (__, ___) => SetState(State.Communicating),
                                                                                      (address, characteristicUuid, bytes) =>
                {
                    onDataReceived?.Invoke(new Data
                    {
                        Characteristic = characteristic,
                        RawData        = bytes
                    });
                });
            });
        }