void UpdatedState(object sender, EventArgs eventArgs) { Console.Error.WriteLine($"Updated state: {central.State}"); if (central.State == CBCentralManagerState.PoweredOn) { central.ConnectedPeripheral += ConnectedPeripheral; central.FailedToConnectPeripheral += FailedToConnectPeripheral; if (uuidOfPeripheralToConnectTo != null) { var uuid = new NSUuid(uuidOfPeripheralToConnectTo); var peripherals = central.RetrievePeripheralsWithIdentifiers(uuid); if (peripherals.Length == 1) { Console.Error.WriteLine($"Connecting to known peripheral with UUID {uuid}"); var peripheral = peripherals[0]; discoveredPeripherals.Add(peripheral); central.ConnectPeripheral(peripheral); return; } else { // Somehow we've lost the peripheral from the list of known peripherals. // We probably need to do handshake all over. firstConnect = true; } } Console.Error.WriteLine("Scanning for peripherals"); central.DiscoveredPeripheral += DiscoveredPeripheral; central.ScanForPeripherals(new CBUUID[0]); } }
public Task <bool> Connect(OWBaseBoard board, CancellationToken cancellationToken) { _requestingDisconnect = false; _reconnecting = false; _connectionCompletionSource = new TaskCompletionSource <bool>(); if (board.NativePeripheral is CBPeripheral peripheral) { _board = board; _peripheral = peripheral; _peripheral.WeakDelegate = this; var options = new PeripheralConnectionOptions() { NotifyOnDisconnection = true, #if __IOS__ NotifyOnConnection = true, NotifyOnNotification = true, #endif }; _centralManager.ConnectPeripheral(peripheral, options); } else { _connectionCompletionSource.SetResult(false); } return(_connectionCompletionSource.Task); }
public async Task <IEnumerable <IGattService> > ConnectAndDiscoverServicesAsync(CancellationToken token) { lock (_lock) { if (State != BluetoothLEDeviceState.Disconnected) { return(null); } State = BluetoothLEDeviceState.Connecting; _centralManager.ConnectPeripheral(_peripheral, new PeripheralConnectionOptions { NotifyOnConnection = true, NotifyOnDisconnection = true }); _connectCompletionSource = new TaskCompletionSource <IEnumerable <IGattService> >(TaskCreationOptions.RunContinuationsAsynchronously); token.Register(() => { lock (_lock) { DisconnectInternal(); _connectCompletionSource?.SetResult(null); } }); } var result = await _connectCompletionSource.Task; _connectCompletionSource = null; return(result); }
public void Connect(BluetoothDevice device) { if (_peripherialMap.ContainsKey(device)) { _manager.ConnectPeripheral(_peripherialMap [device]); } }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { Console.WriteLine("Discovered {0}, data {1}, RSSI {2}", peripheral.Identifier, advertisementData, RSSI); //Connect to peripheral, triggering call to ConnectedPeripheral event handled above _mgr.ConnectPeripheral(peripheral); }
public async Task ConnectTo(CBPeripheral peripheral) { var taskCompletion = new TaskCompletionSource <bool>(); var task = taskCompletion.Task; EventHandler <CBPeripheralEventArgs> connectedHandler = (s, e) => { if (e.Peripheral.Identifier?.ToString() == peripheral.Identifier?.ToString()) { _connectedPeripheral = e.Peripheral; taskCompletion.SetResult(true); } }; try { _manager.ConnectedPeripheral += connectedHandler; _manager.ConnectPeripheral(peripheral); await this.WaitForTaskWithTimeout(task, ConnectionTimeout); Debug.WriteLine($"Bluetooth device connected = {peripheral.Name}"); } finally { _manager.ConnectedPeripheral -= connectedHandler; } }
public void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { if (!peripherals.Contains(peripheral) && !string.IsNullOrWhiteSpace(peripheral.Name) && peripheral.Name.StartsWith("ACR", StringComparison.Ordinal)) { centralManager.ConnectPeripheral(peripheral); peripherals.Add(peripheral); } }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { Console.WriteLine("1"); Console.WriteLine("Peripheral: " + peripheral.Identifier.AsString() + " UUID = " + peripheral.Identifier + " Name = " + peripheral.Name); StopS("Methode DiscoveredPeripheral"); Console.WriteLine("Start connecting"); manager.ConnectPeripheral(peripheral, (PeripheralConnectionOptions)null); }
/// <summary> /// Connect to a device. /// </summary> /// <param name="device">The device.</param> public void ConnectToDevice(IDevice device) { var peripheral = (CBPeripheral)device.NativeDevice; if (peripheral == null) { return; } _centralManager.ConnectPeripheral(peripheral); }
public static void Connect(CBPeripheral peripheral) { if (BleClient.peripheral != null) { return; } BleClient.peripheral = peripheral; manager.StopScan(); manager.ConnectPeripheral(peripheral); }
public async Task ConnectToDevice(Device device) { if (device.Connected) { return; } var nativeDevice = (CBPeripheral)device.NativeDevice; _centralManager.ConnectPeripheral(nativeDevice); await WaitForConnection(); await MapDevice(device, nativeDevice); }
protected override Task ConnectToDeviceNativeAsync(IDevice device, bool autoconnect, CancellationToken cancellationToken) { if (autoconnect) { Trace.Message("Warning: Autoconnect is not supported in iOS"); } _deviceOperationRegistry[device.Id.ToString()] = device; _centralManager.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); return(Task.FromResult(true)); }
public async Task <bool> ConnectAsync(RomeRemoteSystem system) { _tsc = new TaskCompletionSource <bool>(); _manager.StopScan(); myDel.Connected = (s) => { _tsc.TrySetResult(true); }; _manager.ConnectPeripheral((CBPeripheral)system.NativeObject); return(await _tsc.Task); }
public Task ConnectToDeviceAsync(IBTDevice device, CancellationToken cancellationToken = default) { if (device != null) { centralManager.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); cancellationToken.Register(() => { Console.WriteLine("Canceling the connect attempt"); centralManager.CancelPeripheralConnection(device.NativeDevice as CBPeripheral); }); } return(Task.FromResult(true)); }
public bool ConnectDevice(BleDevice device) { // find the device in the list var discovered = _Discovered.FirstOrDefault(d => d.Peripheral.UUID.Uuid.Equals(device.Guid)); if (discovered == null) { return(false); } // connect the device _CentralManager.ConnectPeripheral(discovered.Peripheral); _Connected.Add(discovered.Peripheral); return(true); }
void DiscoveredPeripheral(object sender, CBDiscoveredPeripheralEventArgs e) { var peripheral = e.Peripheral; var device = new BleDevice() { Uuid = peripheral.Identifier.ToString(), Name = peripheral.Name, State = "Connecting...", }; devices.Add(device.Uuid, device); manager.ConnectPeripheral(peripheral, new PeripheralConnectionOptions()); OnSomethingHappened(); }
public async void ConnectToDevice(IDevice device) { _isConnecting = true; //TODO: if it doesn't connect after 10 seconds, cancel the operation // (follow the same model we do for scanning). _central.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); // // in 10 seconds, stop the connection await Task.Delay(5000); // // // if we're still trying to connect if (_isConnecting) { Console.WriteLine("BluetoothLEManager: Connect timeout has elapsed."); ConnectTimeoutElapsed(this, new EventArgs()); } }
/// <summary> /// Connect to a device. /// </summary> /// <param name="device">The device.</param> public async void ConnectToDevice(IDevice device) { var peripheral = device.NativeDevice as CBPeripheral; _central.ConnectPeripheral(peripheral); await Task.Delay(ConnectionTimeout); if (ConnectedDevices.All(x => x.Id != device.Id)) { _central.CancelPeripheralConnection(peripheral); var args = new DeviceConnectionEventArgs(device) { ErrorMessage = "The device connection timed out." }; DeviceFailedToConnect(this, args); } }
public async Task <IEnumerable <IGattService> > ConnectAndDiscoverServicesAsync( bool autoConnect, Action <Guid, byte[]> onCharacteristicChanged, Action <IBluetoothLEDevice> onDeviceDisconnected, CancellationToken token) { using (token.Register(() => { lock (_lock) { Disconnect(); _connectCompletionSource?.TrySetResult(null); } })) { lock (_lock) { if (State != BluetoothLEDeviceState.Disconnected) { return(null); } _onCharacteristicChanged = onCharacteristicChanged; _onDeviceDisconnected = onDeviceDisconnected; State = BluetoothLEDeviceState.Connecting; _centralManager.ConnectPeripheral(_peripheral, new PeripheralConnectionOptions { NotifyOnConnection = true, NotifyOnDisconnection = true }); _connectCompletionSource = new TaskCompletionSource <IEnumerable <IGattService> >(TaskCreationOptions.RunContinuationsAsynchronously); } var result = await _connectCompletionSource.Task; lock (_lock) { _connectCompletionSource = null; return(result); } } }
public bool openConnection(string ids) { throw new NotImplementedException(); #pragma warning disable CS0162 // Se ha detectado código inaccesible foreach (CBPeripheral p in discoveredDevices) #pragma warning restore CS0162 // Se ha detectado código inaccesible { if (p.UUID.Equals(CBUUID.FromString(ids))) { CurrentPeripheral = p; } } if (CurrentPeripheral != null) { bluetoothManager.ConnectPeripheral(CurrentPeripheral); } // List<CBPeripheral> peri= bluetoothManager.RetrieveConnectedPeripherals(); // CBPeripheral peripheral = bluetoothManager.RetrievePeripherals(CBUUID.FromString(ids)); //bluetoothManager.ConnectPeripheral }
public void connect(string deviceAddress) { if (connectedPeripheral != null) { disconnect(); } var dev = devices.FirstOrDefault((item) => item.Identifier.ToString().ToUpper().Equals(deviceAddress.ToUpper())); if (dev == null) { return; } connectedPeripheral = dev; // Make sure we have a reference to this so that it can be canceled while connection is pending var options = new PeripheralConnectionOptions(); options.NotifyOnConnection = true; options.NotifyOnDisconnection = true; options.NotifyOnNotification = true; centralManager.ConnectPeripheral(dev, options); }
protected override Task ConnectToDeviceNativeAsync(IDevice device, ConnectParameters connectParameters, CancellationToken cancellationToken) { if (connectParameters.AutoConnect) { Trace.Message("Warning: Autoconnect is not supported in iOS"); } _deviceOperationRegistry[device.Id.ToString()] = device; if (cancellationToken != CancellationToken.None) { cancellationToken.Register(() => { _centralManager.CancelPeripheralConnection(device.NativeDevice as CBPeripheral); }); } _centralManager.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); return(Task.FromResult(true)); }
protected override Task ConnectToDeviceNativeAsync(IDevice device, ConnectParameters connectParameters, CancellationToken cancellationToken) { if (connectParameters.AutoConnect) { Trace.Message("Warning: Autoconnect is not supported in iOS"); } _deviceOperationRegistry[device.Id.ToString()] = device; // this is dirty: We should not assume, AdapterBase is doing the cleanup for us... // move ConnectToDeviceAsync() code to native implementations. cancellationToken.Register(() => { Trace.Message("Canceling the connect attempt"); _centralManager.CancelPeripheralConnection(device.NativeDevice as CBPeripheral); }); _centralManager.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); return(Task.FromResult(true)); }
public SearchViewController(IntPtr handle) : base(handle) { mCentralManager = new CBCentralManager(DispatchQueue.CurrentQueue); mDiscoveredDevices = new List <CBPeripheral> (); mCentralManager.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine("Discovered Peripheral " + e.Peripheral.Identifier); mDiscoveredDevices.Add(e.Peripheral); DeviceDiscovered(this, e); }; // 55BC208A-5FB5-5619-FDF9-106345844366 // 55BC208A-5FB5-5619-FDF9-106345844366 mCentralManager.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine("UpdatedState: " + mCentralManager.State); }; mCentralManager.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine("Connected Peripheral: " + e.Peripheral.Name); if (!mDiscoveredDevices.Contains(e.Peripheral)) { mDiscoveredDevices.Add(e.Peripheral); mCentralManager.ConnectPeripheral(e.Peripheral, (NSDictionary)null); } DeviceConnected(sender, e); }; mCentralManager.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine("Disconnected Peripheral: " + e.Peripheral.Name); if (mDiscoveredDevices.Contains(e.Peripheral)) { mDiscoveredDevices.Remove(e.Peripheral); } DeviceDisconnected(sender, e); }; isScanning = false; }
public Task <bool> ConnectAsync(string name, string mac) { foreach (var device in _nativeDevices) { if (name != device.Name || mac != device.Identifier.AsString()) { continue; } try { _manager.ConnectPeripheral(device); } catch (Exception e) { Console.WriteLine(e); return(Task.FromResult(false)); } } return(Task.FromResult(false)); }
public void ConnectToPeripheral(IBLEPeripheral peripheral) { nativeManager.ConnectPeripheral(((peripheral as BLEPeripheral).NativePeripheral as CBPeripheral)); }
public Task ConnectAsync() { deviceTaskCompletitionSource.ConnectTCS = new TaskCompletionSource <object>(); _centralManager.ConnectPeripheral(_device); return(deviceTaskCompletitionSource.ConnectTCS.Task); }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { peripheral.DiscoveredService += (sender, e) => { try { if (e.Error == null) { // discover characteristics for newly discovered services foreach (CBService service in peripheral.Services) { if (service.UUID.Equals(_probe.DeviceIdService.UUID)) { peripheral.DiscoverCharacteristics(new CBUUID[] { _probe.DeviceIdCharacteristic.UUID }, service); } } } else { throw new Exception("Error while discovering service: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while discovering characteristics: " + ex.Message, LoggingLevel.Normal, GetType()); DisconnectPeripheral(central, peripheral); } }; peripheral.DiscoveredCharacteristic += (sender, e) => { try { if (e.Error == null) { // read device ID for newly discovered characteristics foreach (CBCharacteristic characteristic in e.Service.Characteristics) { if (characteristic.UUID.Equals(_probe.DeviceIdCharacteristic.UUID)) { peripheral.ReadValue(characteristic); } } } else { throw new Exception("Error while discovering characteristic: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading device ID value from peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); DisconnectPeripheral(central, peripheral); } }; peripheral.UpdatedCharacterteristicValue += (sender, e) => { try { if (e.Error == null) { // characteristic should have a non-null value if (e.Characteristic.Value == null) { throw new Exception("Null updated value for characteristic."); } else { string encounteredDeviceId = Encoding.UTF8.GetString(e.Characteristic.Value.ToArray()); DeviceIdEncountered?.Invoke(this, new BluetoothDeviceProximityDatum(DateTime.UtcNow, encounteredDeviceId)); } } else { throw new Exception("Error while updating characteristic value: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reporting encountered device ID: " + ex.Message, LoggingLevel.Normal, GetType()); } finally { DisconnectPeripheral(central, peripheral); } }; try { central.ConnectPeripheral(peripheral); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while connecting to peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); } }
public async Task <List <Tuple <string, DateTimeOffset> > > ReadPeripheralCharacteristicValuesAsync(CancellationToken cancellationToken) { List <Tuple <string, DateTimeOffset> > characteristicValueTimestamps = new List <Tuple <string, DateTimeOffset> >(); // copy list of peripherals to read. note that the same device may be reported more than once. read each once. List <Tuple <CBPeripheral, CBCentralManager, DateTimeOffset> > peripheralCentralTimestamps; lock (_peripheralCentralTimestamps) { peripheralCentralTimestamps = _peripheralCentralTimestamps.GroupBy(peripheralCentralTimestamp => peripheralCentralTimestamp.Item1.Identifier).Select(group => group.First()).ToList(); } _probe.ReadAttemptCount += peripheralCentralTimestamps.Count; // read characteristic from each peripheral foreach (Tuple <CBPeripheral, CBCentralManager, DateTimeOffset> peripheralCentralTimestamp in peripheralCentralTimestamps) { if (cancellationToken.IsCancellationRequested) { break; } TaskCompletionSource <string> readCompletionSource = new TaskCompletionSource <string>(); CBPeripheral peripheral = peripheralCentralTimestamp.Item1; CBCentralManager central = peripheralCentralTimestamp.Item2; DateTimeOffset timestamp = peripheralCentralTimestamp.Item3; #region discover services peripheral.DiscoveredService += (sender, e) => { try { if (e.Error == null) { SensusServiceHelper.Get().Logger.Log("Discovered services. Discovering characteristics...", LoggingLevel.Normal, GetType()); // discover characteristics for newly discovered services that match the one we're looking for foreach (CBService service in peripheral.Services) { if (service.UUID.Equals(_service.UUID)) { peripheral.DiscoverCharacteristics(new CBUUID[] { _characteristic.UUID }, service); } } } else { throw new Exception("Error while discovering services: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while discovering characteristics: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion #region discover characteristics peripheral.DiscoveredCharacteristic += (sender, e) => { try { if (e.Error == null) { SensusServiceHelper.Get().Logger.Log("Discovered characteristics. Reading value...", LoggingLevel.Normal, GetType()); // read characteristic value for newly discovered characteristics that match the one we're looking for foreach (CBCharacteristic characteristic in e.Service.Characteristics) { if (characteristic.UUID.Equals(_characteristic.UUID)) { peripheral.ReadValue(characteristic); } } } else { throw new Exception("Error while discovering characteristics: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading characteristic values from peripheral: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion #region update characteristic value peripheral.UpdatedCharacterteristicValue += (sender, e) => { try { if (e.Error == null) { // characteristic should have a non-null value if (e.Characteristic.Value == null) { throw new Exception("Null updated value for characteristic."); } else { SensusServiceHelper.Get().Logger.Log("Value read.", LoggingLevel.Normal, GetType()); string characteristicValue = Encoding.UTF8.GetString(e.Characteristic.Value.ToArray()); readCompletionSource.SetResult(characteristicValue); } } else { throw new Exception("Error while updating characteristic value: " + e.Error); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reporting characteristic value: " + ex.Message, LoggingLevel.Normal, GetType()); } }; #endregion try { SensusServiceHelper.Get().Logger.Log("Connecting to peripheral...", LoggingLevel.Normal, GetType()); central.ConnectPeripheral(peripheral); string characteristicValue = await BluetoothDeviceProximityProbe.CompleteReadAsync(readCompletionSource, cancellationToken); if (characteristicValue != null) { characteristicValueTimestamps.Add(new Tuple <string, DateTimeOffset>(characteristicValue, timestamp)); _probe.ReadSuccessCount++; } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral: " + ex, LoggingLevel.Normal, GetType()); } finally { DisconnectPeripheral(central, peripheral); } } return(characteristicValueTimestamps); }
public void ConnectToDevice(IDevice device, bool autoconnect) { //ToDo autoconnect DeviceOperationRegistry[device.ID.ToString()] = device; _central.ConnectPeripheral(device.NativeDevice as CBPeripheral, new PeripheralConnectionOptions()); }
public void ConnectPeripheral(CBCentralManager manager, CBPeripheral peripheral) { manager.ConnectPeripheral(peripheral); }