/// <summary> /// Unregister from a given characteristic /// </summary> public static void Unsubscribe(Characteristic characteristic) { CheckIfInitialized(); BluetoothLEHardwareInterface.UnSubscribeCharacteristic(characteristic.Device.Address, characteristic.ServiceUuid, characteristic.CharacteristicUuid, null); }
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); } }); }
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(); } }); } }); }
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"); }); }
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"; } }
// 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 WriteCharacteristic(byte[] data) { BluetoothLEHardwareInterface.WriteCharacteristic(deviceAddress, ServiceUUID, RXUUID, data.ToArray(), data.Length, true, (characteristicUUID) => { BluetoothLEHardwareInterface.Log("Write Succeeded with characteristic: " + characteristicUUID); }); }
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, ")" })); } } }
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); }
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"); } }
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); }
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); }
/// <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); }); }); }
/// <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(); }); }
//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); }
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); } } }
//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); }
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)); }
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); } ); }
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); }
public void DeinitializeBluetooth() { BluetoothLEHardwareInterface.DeInitialize(() => { Debug.Log("Bluetooth has shut down."); }); }
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 }
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); }); }
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"); }); }
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"); }); }
public void SendByteR(byte value) { byte[] data = new byte[] { value }; BluetoothLEHardwareInterface.WriteCharacteristic(device_right.Address, FullUUID(ServiceUUID), FullUUID(WriteCharacteristic), data, data.Length, true, (characteristicUUID) => { }); }
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; }); }
/// <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 }); }); }); }