public BluetoothConnectionHandler(CBCentralManager centralManager) { _connectedPeripheralTaskSource = new TaskCompletionSource<CBPeripheral>(); _centralManager = centralManager; _centralManager.ConnectedPeripheral += OnConnectedPeripheral; _centralManager.FailedToConnectPeripheral += OnFailedToConnectPeripheral; }
public override void UpdatedState(CBCentralManager mgr) { Console.WriteLine ("UpdatedState()"); string message = null; switch (mgr.State) { case CBCentralManagerState.PoweredOn: message = "Bluetooth PoweredOn."; break; case CBCentralManagerState.Unsupported: message = "The platform or hardware does not support Bluetooth Low Energy."; break; case CBCentralManagerState.Unauthorized: message = "The application is not authorized to use Bluetooth Low Energy."; break; case CBCentralManagerState.PoweredOff: message = "Bluetooth is currently powered off."; break; default: break; } if (message != null) { Console.WriteLine(message); } }
public PeripheralConnectionManager(CBCentralManager manager) { _manager = manager; _peripheralHandlerList = new List<PeripheralHandler>(); manager.ConnectedPeripheral += (sender, args) => OnConnectionUpdated(args.Peripheral); manager.DisconnectedPeripheral += (sender, args) => OnConnectionUpdated(args.Peripheral); }
public void Initialize(Action onStateUpdated) { CentralManager = new CBCentralManager(); ConnectionManager = new PeripheralConnectionManager(CentralManager); _onStateUpdated = onStateUpdated; CentralManager.UpdatedState += OnUpdatedState; }
public static void ScanForHeartRateMonitors (CBCentralManager manager) { if (manager == null) { throw new ArgumentNullException ("manager"); } manager.ScanForPeripherals (PeripheralUUID); }
public ViewController(IntPtr handle) : base(handle) { del = new ChoirCBCentralManagerDelegate(); manager = new CBCentralManager (del, DispatchQueue.CurrentQueue); peripheralManagerDelegate = new ChoirCBPeripheralManagerDelegate (); peripheral = new CBPeripheralManager (peripheralManagerDelegate, DispatchQueue.CurrentQueue); }
static DeviceInformation() { stateHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset); _manager = new CBCentralManager(); //_manager.RetrievedConnectedPeripherals += _manager_RetrievedConnectedPeripherals; //_manager.RetrievedPeripherals += _manager_RetrievedPeripherals; _manager.UpdatedState += _manager_UpdatedState; _manager.DiscoveredPeripheral += _manager_DiscoveredPeripheral; }
protected Adapter () { this._central = new CBCentralManager (DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine ("DiscoveredPeripheral: " + e.Peripheral.Name); Device d = new Device(e.Peripheral); if(!ContainsDevice(this._discoveredDevices, e.Peripheral ) ){ this._discoveredDevices.Add (d); this.DeviceDiscovered(this, new DeviceDiscoveredEventArgs() { Device = d }); } }; _central.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine ("UpdatedState: " + _central.State); stateChanged.Set (); }; _central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine ("ConnectedPeripheral: " + e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if(!ContainsDevice(this._connectedDevices, e.Peripheral ) ){ Device d = new Device(e.Peripheral); this._connectedDevices.Add (new Device(e.Peripheral)); // raise our connected event this.DeviceConnected ( sender, new DeviceConnectionEventArgs () { Device = d } ); } }; _central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine ("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. IDevice foundDevice = null; foreach (var d in this._connectedDevices) { if (d.ID == Guid.ParseExact(e.Peripheral.Identifier.AsString(), "d")) foundDevice = d; } if (foundDevice != null) this._connectedDevices.Remove(foundDevice); // raise our disconnected event this.DeviceDisconnected (sender, new DeviceConnectionEventArgs() { Device = new Device(e.Peripheral) }); }; _central.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { // raise the failed to connect event this.DeviceFailedToConnect(this, new DeviceConnectionEventArgs() { Device = new Device (e.Peripheral), ErrorMessage = e.Error.Description }); }; }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothLE.iOS.Adapter"/> class. /// </summary> public Adapter() { _central = new CBCentralManager(); _central.DiscoveredPeripheral += DiscoveredPeripheral; _central.UpdatedState += UpdatedState; _central.ConnectedPeripheral += ConnectedPeripheral; _central.DisconnectedPeripheral += DisconnectedPeripheral; _central.FailedToConnectPeripheral += FailedToConnectPeripheral; ConnectedDevices = new List<IDevice>(); _stateChanged = new AutoResetEvent(false); _current = this; }
public HeartRateMonitor (CBCentralManager manager, CBPeripheral peripheral) { if (manager == null) { throw new ArgumentNullException ("manager"); } else if (peripheral == null) { throw new ArgumentNullException ("peripheral"); } Location = HeartRateMonitorLocation.Unknown; Manager = manager; Peripheral = peripheral; Peripheral.Delegate = this; Peripheral.DiscoverServices (); }
public void ScanForBroadcasters(CBCentralManager mgr, UIButton Scanner) { //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs mgr.ScanForPeripherals (cbuuids); //Initiates async calls of DiscoveredPeripheral Scanner.SetTitle("Started scan Scan", UIControlState.Normal); //Timeout after 30 seconds var timer = new Timer (30 * 1000); //mgr.StopScan (); timer.Elapsed += (sender, e) => { Console.WriteLine("Stopping scan"); mgr.StopScan (); Console.WriteLine("Scan stopped"); Scanner.SetTitle("Stopped Scan", UIControlState.Normal); }; }
protected BluetoothLeManager() { CentralBleManager = new CBCentralManager(DispatchQueue.CurrentQueue); DiscoveredDevices = new List<CBPeripheral>(); CentralBleManager.DiscoveredPeripheral += (sender, e) => { Mvx.Trace("DiscoveredPeripheral: {0}", e.Peripheral.Name); DiscoveredDevices.Add(e.Peripheral); DeviceDiscovered(this, e); }; CentralBleManager.UpdatedState += (sender, e) => { Mvx.Trace("UpdatedState: {0}", CentralBleManager.State); }; CentralBleManager.ConnectedPeripheral += (sender, e) => { Mvx.Trace("ConnectedPeripheral: " + e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if (!ConnectedDevices.Contains(e.Peripheral)) { ConnectedDevices.Add(e.Peripheral); } // raise our connected event DeviceConnected(sender, e); }; CentralBleManager.DisconnectedPeripheral += (sender, e) => { Mvx.Trace("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. if (ConnectedDevices.Contains(e.Peripheral)) { ConnectedDevices.Remove(e.Peripheral); } // raise our disconnected event DeviceDisconnected(sender, e); }; }
protected BluetoothLEManager () { _central = new CBCentralManager (DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine ("DiscoveredPeripheral: " + e.Peripheral.Name); Console.WriteLine ("RSSI: " + e.Peripheral.RSSI); this._discoveredDevices.Add (e.Peripheral); this.DeviceDiscovered(this, e); }; _central.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine ("UpdatedState: " + _central.State); }; _central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine ("ConnectedPeripheral: " + e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if(!this._connectedDevices.Contains(e.Peripheral) ) { this._connectedDevices.Add (e.Peripheral ); } // raise our connected event this.DeviceConnected ( sender, e); }; _central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine ("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. if ( this._connectedDevices.Contains (e.Peripheral) ) { this._connectedDevices.Remove ( e.Peripheral); } // raise our disconnected event this.DeviceDisconnected (sender, e); }; }
private volatile bool _isScanning; //ToDo maybe lock public Adapter() { ScanTimeout = 10000; DeviceOperationRegistry = new Dictionary <string, IDevice>(); DeviceConnectionRegistry = new Dictionary <string, IDevice>(); _central = new CBCentralManager(DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (sender, e) => { Mvx.Trace("DiscoveredPeripheral: {0}, ID: {1}", e.Peripheral.Name, e.Peripheral.Identifier); var name = e.Peripheral.Name; if (e.AdvertisementData.ContainsKey(CBAdvertisement.DataLocalNameKey)) { // iOS caches the peripheral name, so it can become stale (if changing) // keep track of the local name key manually name = ((NSString)e.AdvertisementData.ValueForKey(CBAdvertisement.DataLocalNameKey)).ToString(); } var d = new Device(e.Peripheral, name, e.RSSI.Int32Value, ParseAdvertismentData(e.AdvertisementData)); DeviceAdvertised(this, new DeviceDiscoveredEventArgs { Device = d }); if (ContainsDevice(_discoveredDevices, e.Peripheral)) { return; } _discoveredDevices.Add(d); DeviceDiscovered(this, new DeviceDiscoveredEventArgs { Device = d }); }; _central.UpdatedState += (sender, e) => { Mvx.Trace("UpdatedState: {0}", _central.State); _stateChanged.Set(); }; _central.ConnectedPeripheral += (sender, e) => { Mvx.Trace("ConnectedPeripherial: {0}", e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals var guid = ParseDeviceGuid(e.Peripheral).ToString(); IDevice device = null; if (DeviceOperationRegistry.TryGetValue(guid, out device)) { DeviceOperationRegistry.Remove(guid); } //ToDo use the same instance of the device just update var d = new Device(e.Peripheral, e.Peripheral.Name, e.Peripheral.RSSI != null ? e.Peripheral.RSSI.Int32Value : 0, device != null ? device.AdvertisementRecords.ToList() : new List <AdvertisementRecord>()); DeviceConnectionRegistry[guid] = d; // raise our connected event DeviceConnected(sender, new DeviceConnectionEventArgs { Device = d }); }; _central.DisconnectedPeripheral += (sender, e) => { if (e.Error != null) { Mvx.Trace(MvxTraceLevel.Error, "Disconnect error {0} {1} {2}", e.Error.Code, e.Error.Description, e.Error.Domain); } // when a peripheral disconnects, remove it from our running list. var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); IDevice foundDevice; // normal disconnect (requested by user) var isNormalDisconnect = DeviceOperationRegistry.TryGetValue(stringId, out foundDevice); if (isNormalDisconnect) { DeviceOperationRegistry.Remove(stringId); } // remove from connected devices if (DeviceConnectionRegistry.TryGetValue(stringId, out foundDevice)) { DeviceConnectionRegistry.Remove(stringId); } if (isNormalDisconnect) { Mvx.Trace("DisconnectedPeripheral by user: {0}", e.Peripheral.Name); DeviceDisconnected(sender, new DeviceConnectionEventArgs { Device = foundDevice }); } else { Mvx.Trace("DisconnectedPeripheral by lost signal: {0}", e.Peripheral.Name); DeviceConnectionLost(sender, new DeviceConnectionEventArgs { Device = foundDevice ?? new Device(e.Peripheral) }); } }; _central.FailedToConnectPeripheral += (sender, e) => { Mvx.Trace(MvxTraceLevel.Warning, "Failed to connect peripheral {0}: {1}", e.Peripheral.Identifier, e.Peripheral.Name); // raise the failed to connect event DeviceConnectionError(this, new DeviceConnectionEventArgs { Device = new Device(e.Peripheral), ErrorMessage = e.Error.Description }); }; }
public BluetoothLEService() { _centralManager = new CBCentralManager(this, DispatchQueue.CurrentQueue); }
public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral) { var device = _peripheralMap[peripheral]; device.OnDeviceConnected(); }
public override void WillRestoreState(CBCentralManager central, NSDictionary dict) { base.WillRestoreState(central, dict); }
protected Adapter () { this._central = new CBCentralManager (DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine ("DiscoveredPeripheral Name: " + e.Peripheral.Name); Console.WriteLine("DiscoveredPeripheral RSSI: " + e.RSSI); Device d = new Device(e.Peripheral); if(!ContainsDevice(this._discoveredDevices, e.Peripheral ) ){ this._discoveredDevices.Add (d); this.DeviceDiscovered(this, new DeviceDiscoveredEventArgs() { Device = d , RSSI = e.RSSI.Int32Value }); } }; _central.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine ("UpdatedState: " + _central.State); stateChanged.Set (); BluetoothLEStates LEState = BluetoothLEStates.Unknown; switch (_central.State) { case CBCentralManagerState.PoweredOn: LEState = BluetoothLEStates.PoweredOn; break; case CBCentralManagerState.PoweredOff: LEState = BluetoothLEStates.PoweredOff; break; case CBCentralManagerState.Resetting: LEState = BluetoothLEStates.Resetting; break; case CBCentralManagerState.Unauthorized: LEState = BluetoothLEStates.Unauthorized; break; case CBCentralManagerState.Unknown: LEState = BluetoothLEStates.Unknown; break; case CBCentralManagerState.Unsupported: LEState = BluetoothLEStates.Unsupported; break; default: LEState = BluetoothLEStates.Unsupported; break; } this.BluetoothStateUpdated(this, new BluetoothStateEventArgs() {BTState = LEState}); }; _central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine ("ConnectedPeripheral: " + e.Peripheral.Name); this.peripheral = e.Peripheral; // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if(!ContainsDevice(this._connectedDevices,this.peripheral ) ){ Device d = new Device(e.Peripheral); this._connectedDevices.Add (new Device(this.peripheral)); // raise our connected event this.DeviceConnected ( sender, new DeviceConnectionEventArgs () { Device = d } ); } }; _central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine ("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. IDevice foundDevice = null; foreach (var d in this._connectedDevices) { if (d.ID == Guid.ParseExact(e.Peripheral.Identifier.AsString(), "d")) foundDevice = d; } if (foundDevice != null) this._connectedDevices.Remove(foundDevice); // raise our disconnected event this.DeviceDisconnected (sender, new DeviceConnectionEventArgs() { Device = new Device(e.Peripheral) }); }; _central.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { // raise the failed to connect event Console.WriteLine ("Failed to connect to Peripheral: " + e.Peripheral.Name); this.DeviceFailedToConnect(this, new DeviceConnectionEventArgs() { Device = new Device (e.Peripheral), ErrorMessage = e.Error.Description }); }; }
public override void UpdatedState(CBCentralManager central) { if(central.State == CBCentralManagerState.PoweredOn) { stateHandle.Set(); } else { stateHandle.Reset(); } }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { Console.WriteLine ("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI); }
public override void FailedToConnectPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error) { }
public override void DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error) { }
public override void RetrievedPeripherals(CBCentralManager central, CBPeripheral[] peripherals) { }
public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral) { }
public void StartScanning() { central = new CBCentralManager(); central.UpdatedState += UpdatedState; }
public void RequestBluetoothAccess () { if (cbManager == null) cbManager = new CBCentralManager (); if (cbManager.State == CBCentralManagerState.PoweredOn) cbManager.ScanForPeripherals (new CBUUID [0]); else { UIAlertView alert = new UIAlertView ("Error", "Bluetooth must be enabled", null, "Okay", null); alert.Show (); } }
public void CheckBluetoothAccess () { if (cbManager == null) cbManager = new CBCentralManager (); CBCentralManagerState state = cbManager.State; switch (state) { case CBCentralManagerState.Unknown: ShowAlert (DataClass.Bluetooth, "unknown"); break; case CBCentralManagerState.Unauthorized: ShowAlert (DataClass.Bluetooth, "denied"); break; default: ShowAlert (DataClass.Bluetooth, "granted"); break; } }
private volatile bool _isScanning; //ToDo maybe lock public Adapter() { ScanTimeout = 10000; DeviceOperationRegistry = new Dictionary<string, IDevice>(); DeviceConnectionRegistry = new Dictionary<string, IDevice>(); _central = new CBCentralManager(DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (sender, e) => { Mvx.Trace("DiscoveredPeripheral: {0}, ID: {1}", e.Peripheral.Name, e.Peripheral.Identifier); var name = e.Peripheral.Name; if (e.AdvertisementData.ContainsKey(CBAdvertisement.DataLocalNameKey)) { // iOS caches the peripheral name, so it can become stale (if changing) // keep track of the local name key manually name = ((NSString)e.AdvertisementData.ValueForKey(CBAdvertisement.DataLocalNameKey)).ToString(); } var d = new Device(e.Peripheral, name, e.RSSI.Int32Value, ParseAdvertismentData(e.AdvertisementData)); DeviceAdvertised(this, new DeviceDiscoveredEventArgs { Device = d }); if (ContainsDevice(_discoveredDevices, e.Peripheral)) { return; } _discoveredDevices.Add(d); DeviceDiscovered(this, new DeviceDiscoveredEventArgs { Device = d }); }; _central.UpdatedState += (sender, e) => { Mvx.Trace("UpdatedState: {0}", _central.State); _stateChanged.Set(); }; _central.ConnectedPeripheral += (sender, e) => { Mvx.Trace("ConnectedPeripherial: {0}", e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals var guid = ParseDeviceGuid(e.Peripheral).ToString(); IDevice device = null; if (DeviceOperationRegistry.TryGetValue(guid, out device)) { DeviceOperationRegistry.Remove(guid); } //ToDo use the same instance of the device just update var d = new Device(e.Peripheral, e.Peripheral.Name, e.Peripheral.RSSI != null ? e.Peripheral.RSSI.Int32Value : 0, device != null ? device.AdvertisementRecords.ToList() : new List<AdvertisementRecord>()); DeviceConnectionRegistry[guid] = d; // raise our connected event DeviceConnected(sender, new DeviceConnectionEventArgs { Device = d }); }; _central.DisconnectedPeripheral += (sender, e) => { if (e.Error != null) { Mvx.Trace(MvxTraceLevel.Error, "Disconnect error {0} {1} {2}", e.Error.Code, e.Error.Description, e.Error.Domain); } // when a peripheral disconnects, remove it from our running list. var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); IDevice foundDevice; // normal disconnect (requested by user) var isNormalDisconnect = DeviceOperationRegistry.TryGetValue(stringId, out foundDevice); if (isNormalDisconnect) { DeviceOperationRegistry.Remove(stringId); } // remove from connected devices if (DeviceConnectionRegistry.TryGetValue(stringId, out foundDevice)) { DeviceConnectionRegistry.Remove(stringId); } if (isNormalDisconnect) { Mvx.Trace("DisconnectedPeripheral by user: {0}", e.Peripheral.Name); DeviceDisconnected(sender, new DeviceConnectionEventArgs { Device = foundDevice }); } else { Mvx.Trace("DisconnectedPeripheral by lost signal: {0}", e.Peripheral.Name); DeviceConnectionLost(sender, new DeviceConnectionEventArgs { Device = foundDevice ?? new Device(e.Peripheral) }); } }; _central.FailedToConnectPeripheral += (sender, e) => { Mvx.Trace(MvxTraceLevel.Warning, "Failed to connect peripheral {0}: {1}", e.Peripheral.Identifier, e.Peripheral.Name); // raise the failed to connect event DeviceConnectionError(this, new DeviceConnectionEventArgs { Device = new Device(e.Peripheral), ErrorMessage = e.Error.Description }); }; }
public void ConnectPeripheral(CBCentralManager manager, CBPeripheral peripheral) { manager.ConnectPeripheral(peripheral); }
public override void UpdatedState(CBCentralManager central) { // see http://docs.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events // NOTE: Don't call the base implementation on a Model class // throw new NotImplementedException (); }
public override void DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error) { System.Diagnostics.Debug.WriteLine($"Disconnected {peripheral.Identifier} {error}"); Bluetooth.DisconnectedPeripheral?.Invoke(central, new CBPeripheralErrorEventArgs(peripheral, error)); }
public override void RetrievedConnectedPeripherals(CBCentralManager central, CBPeripheral[] peripherals) { base.RetrievedConnectedPeripherals(central, peripherals); }
public Adapter(CBCentralManager centralManager) { _centralManager = centralManager; _centralManager.DiscoveredPeripheral += (sender, e) => { Trace.Message("DiscoveredPeripheral: {0}, Id: {1}", e.Peripheral.Name, e.Peripheral.Identifier); var name = e.Peripheral.Name; if (e.AdvertisementData.ContainsKey(CBAdvertisement.DataLocalNameKey)) { // iOS caches the peripheral name, so it can become stale (if changing) // keep track of the local name key manually name = ((NSString)e.AdvertisementData.ValueForKey(CBAdvertisement.DataLocalNameKey)).ToString(); } var device = new Device(this, e.Peripheral, name, e.RSSI.Int32Value, ParseAdvertismentData(e.AdvertisementData)); HandleDiscoveredDevice(device); }; _centralManager.UpdatedState += (sender, e) => { Trace.Message("UpdatedState: {0}", _centralManager.State); _stateChanged.Set(); }; _centralManager.ConnectedPeripheral += (sender, e) => { Trace.Message("ConnectedPeripherial: {0}", e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals var guid = ParseDeviceGuid(e.Peripheral).ToString(); IDevice device; if (_deviceOperationRegistry.TryGetValue(guid, out device)) { _deviceOperationRegistry.Remove(guid); ((Device)device).Update(e.Peripheral); } else { Trace.Message("Device not found in operation registry. Creating a new one."); device = new Device(this, e.Peripheral); } _deviceConnectionRegistry[guid] = device; HandleConnectedDevice(device); }; _centralManager.DisconnectedPeripheral += (sender, e) => { if (e.Error != null) { Trace.Message("Disconnect error {0} {1} {2}", e.Error.Code, e.Error.Description, e.Error.Domain); } // when a peripheral disconnects, remove it from our running list. var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); IDevice foundDevice; // normal disconnect (requested by user) var isNormalDisconnect = _deviceOperationRegistry.TryGetValue(stringId, out foundDevice); if (isNormalDisconnect) { _deviceOperationRegistry.Remove(stringId); } // remove from connected devices if (_deviceConnectionRegistry.TryGetValue(stringId, out foundDevice)) { _deviceConnectionRegistry.Remove(stringId); } foundDevice = foundDevice ?? new Device(this, e.Peripheral); //make sure all cached services are cleared ((Device)foundDevice).ClearServices(); HandleDisconnectedDevice(isNormalDisconnect, foundDevice); }; _centralManager.FailedToConnectPeripheral += (sender, e) => { var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); IDevice foundDevice; // remove instance from registry if (_deviceOperationRegistry.TryGetValue(stringId, out foundDevice)) { _deviceOperationRegistry.Remove(stringId); } foundDevice = foundDevice ?? new Device(this, e.Peripheral); HandleConnectionFail(foundDevice, e.Error.Description); }; }
/// /// Core Bluetooth CBCentralManager callback when we discover a beacon. We're not super /// interested in any error situations at this point in time. /// public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { var serviceData = advertisementData[CBAdvertisement.DataServiceDataKey] as NSDictionary; if (serviceData != null) { var eft = Eddystone.FrameTypeForFrame(serviceData); // If it's a telemetry frame, stash it away and we'll send it along with the next regular // frame we see. Otherwise, process the UID frame. if (eft == BeaconInfo.EddystoneFrameType.TelemetryFrameType) { var data = Eddystone.TelemetryDataForFrame(advertisementData); if (deviceIDCache.ContainsKey(peripheral.Identifier)) { deviceIDCache[peripheral.Identifier] = data; } else { deviceIDCache.Add(peripheral.Identifier, data); } } else if (eft == BeaconInfo.EddystoneFrameType.UIDFrameType || eft == BeaconInfo.EddystoneFrameType.EIDFrameType) { if (!deviceIDCache.ContainsKey(peripheral.Identifier)) { Debug.WriteLine($"deviceIDCache does not contain key: {peripheral.Identifier}."); return; } var telemetry = deviceIDCache[peripheral.Identifier]; var serviceUUID = CBUUID.FromString("FEAA"); var _RSSI = RSSI.Int32Value; var beaconServiceData = serviceData[serviceUUID] as NSData; if (beaconServiceData != null) { var beaconInfo = (eft == BeaconInfo.EddystoneFrameType.UIDFrameType) ? Eddystone.BeaconInfoForUIDFrameData(beaconServiceData, telemetry, _RSSI) : Eddystone.BeaconInfoForEIDFrameData(beaconServiceData, telemetry, _RSSI); if (beaconInfo != null) { // NOTE: At this point you can choose whether to keep or get rid of the telemetry // data. You can either opt to include it with every single beacon sighting // for this beacon, or delete it until we get a new / "fresh" TLM frame. // We'll treat it as "report it only when you see it", so we'll delete it // each time. deviceIDCache.Remove(peripheral.Identifier); if (seenEddystoneCache.ContainsKey(beaconInfo.BeaconId.ToString())) { var value = seenEddystoneCache[beaconInfo.BeaconId.ToString()]?["onLostTimer"]; if (value != null) { var timer = (DispatchTimer)value; timer.Reschedule(); } this.beaconScanner.ScannerDelegate?.DidUpdateBeacon(beaconScanner, beaconInfo); } else { // We've never seen this beacon before this.beaconScanner.ScannerDelegate?.DidFindBeacon(beaconScanner, beaconInfo); var onLostTimer = DispatchTimer.ScheduledDispatchTimer(this.onLostTimout, DispatchQueue.MainQueue, (DispatchTimer obj) => { var cacheKey = beaconInfo.BeaconId.ToString(); if (seenEddystoneCache.ContainsKey(cacheKey)) { var beaconCache = seenEddystoneCache[cacheKey]; var lostBeaconInfo = beaconCache["beaconInfo"] as BeaconInfo; if (beaconCache != null && lostBeaconInfo != null) { this.beaconScanner.ScannerDelegate?.DidLoseBeacon(beaconScanner, beaconInfo); seenEddystoneCache.Remove(beaconInfo.BeaconId.ToString()); } } }); var newMap = new Dictionary <string, object>() { { "beaconInfo", beaconInfo }, { "onLostTimer", onLostTimer } }; if (seenEddystoneCache.ContainsKey(beaconInfo.BeaconId.ToString())) { seenEddystoneCache[beaconInfo.BeaconId.ToString()] = newMap; } else { seenEddystoneCache.Add(beaconInfo.BeaconId.ToString(), newMap); } } } } } else if (eft == BeaconInfo.EddystoneFrameType.URLFrameType) { var serviceUUID = CBUUID.FromString("FEAA"); var _RSSI = RSSI.Int32Value; var beaconServiceData = serviceData[serviceUUID] as NSData; if (beaconServiceData != null) { var url = Eddystone.ParseURLFromFrame(beaconServiceData); if (url != null) { this.beaconScanner.ScannerDelegate?.DidObserveURLBeacon(beaconScanner, url, _RSSI); } } } } else { Debug.WriteLine("Unable to find service data; can't process Eddystone"); } }
public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral) { System.Diagnostics.Debug.WriteLine($"Connected {peripheral.Identifier}"); Bluetooth.ConnectedPeripheral?.Invoke(central, peripheral); }
public BluetoothCommunication() { CentralBTManager = new CBCentralManager(); }
public BluetoothScanner(CBCentralManager manager) { _manager = manager; _manager.DiscoveredPeripheral += OnDiscoveredPeripheral; }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { Console.WriteLine("Discovered {0}, data {1}, RSSI {2}", peripheral.Name, advertisementData, RSSI); }
public override void UpdatedState(CBCentralManager central) { }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothHub"/> class. /// </summary> public BluetoothHub() { this.manager = new CBCentralManager(this, DispatchQueue.MainQueue); }
public override void DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error) { var device = _peripheralMap[peripheral]; device.OnDeviceDisconnected(); }
public BluetoothService() { _bluetoothManager = new CoreBluetooth.CBCentralManager(); }
public BluetoothTableViewSource(RequestDeviceOptions options) { _delegate = new BluetoothDelegate(this); _manager = new CBCentralManager(_delegate, DispatchQueue.MainQueue); _options = options; }
internal Adapter(CBCentralManager centralManager, IBleCentralManagerDelegate bleCentralManagerDelegate) { _centralManager = centralManager; _bleCentralManagerDelegate = bleCentralManagerDelegate; _bleCentralManagerDelegate.DiscoveredPeripheral += (sender, e) => { Trace.Message("DiscoveredPeripheral: {0}, Id: {1}", e.Peripheral.Name, e.Peripheral.Identifier); var name = e.Peripheral.Name; if (e.AdvertisementData.ContainsKey(CBAdvertisement.DataLocalNameKey)) { // iOS caches the peripheral name, so it can become stale (if changing) // keep track of the local name key manually name = ((NSString)e.AdvertisementData.ValueForKey(CBAdvertisement.DataLocalNameKey)).ToString(); } var device = new Device(this, e.Peripheral, _bleCentralManagerDelegate, name, e.RSSI.Int32Value, ParseAdvertismentData(e.AdvertisementData)); HandleDiscoveredDevice(device); }; _bleCentralManagerDelegate.UpdatedState += (sender, e) => { Trace.Message("UpdatedState: {0}", _centralManager.State); _stateChanged.Set(); //handle PoweredOff state //notify subscribers about disconnection if (_centralManager.State == CBCentralManagerState.PoweredOff) { foreach (var device in ConnectedDeviceRegistry.Values.ToList()) { ((Device)device).ClearServices(); HandleDisconnectedDevice(false, device); } ConnectedDeviceRegistry.Clear(); } }; _bleCentralManagerDelegate.ConnectedPeripheral += (sender, e) => { Trace.Message("ConnectedPeripherial: {0}", e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals var guid = ParseDeviceGuid(e.Peripheral).ToString(); Device device; if (_deviceOperationRegistry.TryGetValue(guid, out device)) { _deviceOperationRegistry.Remove(guid); ((Device)device).Update(e.Peripheral); } else { Trace.Message("Device not found in operation registry. Creating a new one."); device = new Device(this, e.Peripheral, _bleCentralManagerDelegate); } ConnectedDeviceRegistry[guid] = device; HandleConnectedDevice(device); }; _bleCentralManagerDelegate.DisconnectedPeripheral += (sender, e) => { if (e.Error != null) { Trace.Message("Disconnect error {0} {1} {2}", e.Error.Code, e.Error.Description, e.Error.Domain); } // when a peripheral disconnects, remove it from our running list. var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); // normal disconnect (requested by user) var isNormalDisconnect = _deviceOperationRegistry.TryGetValue(stringId, out var foundDevice); if (isNormalDisconnect) { _deviceOperationRegistry.Remove(stringId); } // check if it is a peripheral disconnection, which would be treated as normal if (e.Error != null && e.Error.Code == 7 && e.Error.Domain == "CBErrorDomain") { isNormalDisconnect = true; } // remove from connected devices if (!ConnectedDeviceRegistry.TryRemove(stringId, out foundDevice)) { Trace.Message($"Device with id '{stringId}' was not found in the connected device registry. Nothing to remove."); } foundDevice = foundDevice ?? new Device(this, e.Peripheral, _bleCentralManagerDelegate); //make sure all cached services are cleared this will also clear characteristics and descriptors implicitly ((Device)foundDevice).ClearServices(); HandleDisconnectedDevice(isNormalDisconnect, foundDevice); }; _bleCentralManagerDelegate.FailedToConnectPeripheral += (sender, e) => { var id = ParseDeviceGuid(e.Peripheral); var stringId = id.ToString(); // remove instance from registry if (_deviceOperationRegistry.TryGetValue(stringId, out var foundDevice)) { _deviceOperationRegistry.Remove(stringId); } foundDevice = foundDevice ?? new Device(this, e.Peripheral, _bleCentralManagerDelegate); HandleConnectionFail(foundDevice, e.Error.Description); }; }
public void Request() { var manager = new CBCentralManager(); }
public BluetoothHub() { this.manager = new CBCentralManager(this, DispatchQueue.MainQueue); this.OpenSettings = new Command(o => { }, o => false); }
public Adapter () { this._central = new CBCentralManager (DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine ("DiscoveredPeripheral: " + e.Peripheral.Name); NSString localName = null; try { localName = e.AdvertisementData[CBAdvertisement.DataLocalNameKey] as NSString; } catch { localName = new NSString(e.Peripheral.Name); } Device d = new Device(e.Peripheral, localName); if(!ContainsDevice(this._discoveredDevices, e.Peripheral ) ){ byte[] scanRecord = null; try { Console.WriteLine ("ScanRecords: " + e.AdvertisementData.ToString()); NSError error = null; var soft = Clean(e.AdvertisementData); Console.WriteLine ("ScanRecords cleaned: " + soft.ToString()); var binFormatter = new BinaryFormatter(); var mStream = new MemoryStream(); binFormatter.Serialize(mStream, soft); //This gives you the byte array. scanRecord = mStream.ToArray(); } catch (Exception exception) { Console.WriteLine ("ScanRecords to byte[] failed"); } finally { this._discoveredDevices.Add (d); this.DeviceDiscovered(this, new DeviceDiscoveredEventArgs() { Device = d, RSSI = (int)e.RSSI, ScanRecords = scanRecord }); } } }; _central.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine ("UpdatedState: " + _central.State); stateChanged.Set (); }; _central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine ("ConnectedPeripheral: " + e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if(!ContainsDevice(this._connectedDevices, e.Peripheral ) ){ Device d = new Device(e.Peripheral); this._connectedDevices.Add (new Device(e.Peripheral)); // raise our connected event this.DeviceConnected ( sender, new DeviceConnectionEventArgs () { Device = d } ); } }; _central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine ("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. IDevice foundDevice = null; foreach (var d in this._connectedDevices) { if (d.ID == Guid.ParseExact(e.Peripheral.Identifier.AsString(), "d")) foundDevice = d; } if (foundDevice != null) this._connectedDevices.Remove(foundDevice); // raise our disconnected event this.DeviceDisconnected (sender, new DeviceConnectionEventArgs() { Device = new Device(e.Peripheral) }); }; _central.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { // raise the failed to connect event this.DeviceFailedToConnect(this, new DeviceConnectionEventArgs() { Device = new Device (e.Peripheral), ErrorMessage = e.Error.Description }); }; }
//private Timer scanningTimer override Init() { super.init() centralManager = CBCentralManager(delegate: self, queue: nil) }
public void StartLeClient() { CustomCBCentralManagerDelegate cbCentralManagerDelegate = new CustomCBCentralManagerDelegate(); var myManager = new CBCentralManager(cbCentralManagerDelegate, DispatchQueue.CurrentQueue); }
public override void FailedToConnectPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error) { System.Diagnostics.Debug.WriteLine($"Failed to connect {peripheral.Identifier} {error.Code}"); Bluetooth.FailedToConnectPeripheral?.Invoke(central, peripheral); }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { base.DiscoveredPeripheral(central, peripheral, advertisementData, RSSI); }
public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI) { OnDiscoveredPeripheral(central, peripheral, advertisementData, RSSI); }
protected Adapter() { this._central = new CBCentralManager(MonoTouch.CoreFoundation.DispatchQueue.CurrentQueue); _central.DiscoveredPeripheral += (object sender, CBDiscoveredPeripheralEventArgs e) => { Console.WriteLine("DiscoveredPeripheral: " + e.Peripheral.Name); Device d = new Device(e.Peripheral); if (!ContainsDevice(this._discoveredDevices, e.Peripheral)) { this._discoveredDevices.Add(d); this.DeviceDiscovered(this, new DeviceDiscoveredEventArgs() { Device = d }); } }; _central.UpdatedState += (object sender, EventArgs e) => { Console.WriteLine("UpdatedState: " + _central.State); stateChanged.Set(); }; _central.ConnectedPeripheral += (object sender, CBPeripheralEventArgs e) => { Console.WriteLine("ConnectedPeripheral: " + e.Peripheral.Name); // when a peripheral gets connected, add that peripheral to our running list of connected peripherals if (!ContainsDevice(this._connectedDevices, e.Peripheral)) { Device d = new Device(e.Peripheral); this._connectedDevices.Add(new Device(e.Peripheral)); // raise our connected event this.DeviceConnected(sender, new DeviceConnectionEventArgs() { Device = d }); } }; _central.DisconnectedPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { Console.WriteLine("DisconnectedPeripheral: " + e.Peripheral.Name); // when a peripheral disconnects, remove it from our running list. IDevice foundDevice = null; foreach (var d in this._connectedDevices) { if (d.ID == Guid.ParseExact(e.Peripheral.Identifier.AsString(), "d")) { foundDevice = d; } } if (foundDevice != null) { this._connectedDevices.Remove(foundDevice); } // raise our disconnected event this.DeviceDisconnected(sender, new DeviceConnectionEventArgs() { Device = new Device(e.Peripheral) }); }; _central.FailedToConnectPeripheral += (object sender, CBPeripheralErrorEventArgs e) => { // raise the failed to connect event this.DeviceFailedToConnect(this, new DeviceConnectionEventArgs() { Device = new Device(e.Peripheral), ErrorMessage = e.Error.Description }); }; }
protected override void InitializeNative() { _centralManager = new CBCentralManager(DispatchQueue.CurrentQueue); _centralManager.UpdatedState += (s, e) => State = GetState(); }