Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core method of developing CoreBlueTooth library with iOS Bluetooth?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

What is the core method of developing CoreBlueTooth library with iOS Bluetooth? in order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

I. introduction

Bluetooth is a convenient means of close communication between devices. After the introduction of Bluetooth 4.0 into iPhone, the communication between devices becomes more simple. The related Bluetooth operations are uniformly managed by a special CoreBluetooth.framework. Communication and interaction through Bluetooth is divided into two parties, one is the central device central, the other is the peripheral peripheral, the peripheral sends information to the outside through broadcasting, and the central device retrieves the broadcast information sent by the peripheral, which can be paired and connected, and then carry on the data exchange. Here I wrote a lightweight Bluetooth library, GJLightBlueTooth, which includes basic Bluetooth scan connection operations.

II. Central equipment CBCentralManager

CBCentralManager is the management class of the equipment in the management center. The important methods are as follows:

/ / set the central device agent @ property (assign, nonatomic, nullable) id delegate;// central device current status @ property (readonly) CBCentralManagerState state;// central device is scanning @ property (readonly) BOOL isScanning NS_AVAILABLE (NA, 9x0)

Where state is an enumeration, the status of whether Bluetooth is available is as follows:

Typedef NS_ENUM (NSInteger, CBCentralManagerState) {/ / status unknown CBCentralManagerStateUnknown = 0, / / disconnect is about to reset CBCentralManagerStateResetting, / / the platform does not support Bluetooth CBCentralManagerStateUnsupported, / / Bluetooth uses CBCentralManagerStateUnauthorized without authorization, / / Bluetooth closes CBCentralManagerStatePoweredOff, / / Bluetooth enables CBCentralManagerStatePoweredOn normally,}

The following methods are used to initialize the administrative center:

/ / initialization method / / the set proxy needs to abide by the CBCentralManagerDelegate protocol / / queue can set the Bluetooth scanning thread to pass nil to-(instancetype) initWithDelegate: (nullable id) delegate queue: (nullable dispatch_queue_t) queue in the main thread / / this method is also used in the options dictionary to set some initialization properties of the console / / the supported key values in the dictionary are as follows: / * NSString * const CBCentralManagerOptionShowPowerAlertKey corresponds to a NSNumber type Bool value, which is used to set whether the user prompt NSString * const CBCentralManagerOptionRestoreIdentifierKey corresponds to a NSString object when Bluetooth is turned off. Set the identifier of the administrative center ID*/- (instancetype) initWithDelegate: (nullable id) delegate queue: (nullable dispatch_queue_t) queue options: (nullable NSDictionary *) options / / get all connected devices based on obtaining all known devices-(NSArray *) retrievePeripheralsWithIdentifiers: (NSArray *) identifiers;// based on service id-(NSArray *) retrieveConnectedPeripheralsWithServices: (NSArray *) serviceUUIDs

After initializing the management center, the following methods in the agent will be called back, and we must implement the following methods:

/ / the status of the console can be obtained in this method-(void) centralManagerDidUpdateState: (CBCentralManager *) central

If the console status in the above method is Bluetooth available, you can turn on the scanning peripheral by using the following methods:

/ / serviceUUIDs Peripheral options used to scan a characteristic ID is used to set some scan attribute keys as follows: / * / / whether the Bool value of the corresponding NSNumber is allowed to be scanned repeatedly. The default is NO, which automatically removes NSString * const CBCentralManagerScanOptionAllowDuplicatesKey;// the UUID array of devices to be scanned corresponds to NSArrayNSString * const CBCentralManagerScanOptionSolicitedServiceUUIDsKey;*/- (void) scanForPeripheralsWithServices: (nullable NSArray *) serviceUUIDs options: (nullable NSDictionary *) options;// stops scanning peripherals-(void) stopScan

The result of the scan will be returned in the following proxy method:

/ / Peripheral scanned by peripheral / / advertisementData is broadcast data sent by Peripheral / / RSSI is signal strength-(void) centralManager: (CBCentralManager *) central didDiscoverPeripheral: (CBPeripheral *) peripheral advertisementData: (NSDictionary *) advertisementData RSSI: (NSNumber *) RSSI

After scanning a peripheral, you can connect a peripheral in the following ways:

/ * the initial attribute key values of some connected devices can be set in options as follows: / / Bool values corresponding to NSNumber, whether a warning NSString * const CBConnectPeripheralOptionNotifyOnConnectionKey;// corresponding to NSNumber pops up when the peripheral is connected, whether a warning NSString * const CBConnectPeripheralOptionNotifyOnNotificationKey corresponding to NSNumber pops up when the peripheral is disconnected, and whether a warning NSString * const CBConnectPeripheralOptionNotifyOnNotificationKey pops up when the peripheral pauses the connection. * /-(void) connectPeripheral: (CBPeripheral *) peripheral options: (nullable NSDictionary *) options;// cancel a peripheral connection-(void) cancelPeripheralConnection: (CBPeripheral *) peripheral

After calling the method of connecting peripherals, the following proxy methods will be dropped:

/ / connect the peripheral successfully-(void) centralManager: (CBCentralManager *) central didConnectPeripheral: (CBPeripheral *) peripheral;// connection to the peripheral failed-(void) centralManager: (CBCentralManager *) central didFailToConnectPeripheral: (CBPeripheral *) peripheral error: (nullable NSError *) error;// disconnect the peripheral-(void) centralManager: (CBCentralManager *) central didDisconnectPeripheral: (CBPeripheral *) peripheral error: (nullable NSError *) error

When the Central Administration resumes, the following proxies are invoked:

/ / the following key value pair / * / Peripheral Array NSString * const CBCentralManagerRestoredStatePeripheralsKey;// Restoration connection Service UUID Array NSString * const CBCentralManagerRestoredStateScanServicesKey;// Restoration connection Peripheral scan attribute Dictionary array NSString * const CBCentralManagerRestoredStateScanOptionsKey;*/- (void) centralManager: (CBCentralManager *) central willRestoreState: (NSDictionary *) dict is passed into / / const CBCentralManagerRestoredStateScanServicesKey;//

Third, Peripheral CBPeripheralManager

We know from the above that the central equipment is used to scan the surrounding peripherals. In the communication between the two devices, one must act as the central device, the other as the peripheral, and the peripherals are managed by CBPeripheralManager. The main methods are as follows:

/ / set the peripheral management center agent @ property (assign, nonatomic, nullable) id delegate;// peripheral status enumeration, such as whether the central device @ property (readonly) CBPeripheralManagerState state;// is sending a broadcast @ property (readonly) BOOL isAdvertising;// user's authorization status + (CBPeripheralManagerAuthorizationStatus) authorizationStatus / / the specific meaning of initializing and setting agent parameters and the central equipment management center-(instancetype) initWithDelegate: (nullable id) delegate queue: (nullable dispatch_queue_t);-(instancetype) initWithDelegate: (nullable id) delegate queue: (nullable dispatch_queue_t) queue options: (nullable NSDictionary *) options / / start sending broadcast / / data that can be sent in advertisementData is stipulated as follows / * corresponding to set NSString type broadcast name NSString * const CBAdvertisementDataLocalNameKey; peripheral manufacturer's NSData data NSString * const CBAdvertisementDataManufacturerDataKey; peripheral manufacturer's CBUUID data NSString * const CBAdvertisementDataServiceDataKey; service UUID and its corresponding service data dictionary array NSString * const CBAdvertisementDataServiceUUIDsKey; UUID array NSString * const CBAdvertisementDataOverflowServiceUUIDsKey; peripherals send power NSNumber type NSString * const CBAdvertisementDataTxPowerLevelKey Whether the peripheral can connect to the UUID array of NSString * const CBAdvertisementDataIsConnectable; service NSString * const CBAdvertisementDataSolicitedServiceUUIDsKey;*/- (void) startAdvertising: (nullable NSDictionary *) advertisementData;// stops sending broadcasts-(void) stopAdvertising;// sets the delay enumeration of specific central devices to which a connection is set as follows: / * typedef NS_ENUM (NSInteger, CBPeripheralManagerConnectionLatency) {CBPeripheralManagerConnectionLatencyLow = 0, CBPeripheralManagerConnectionLatencyMedium, CBPeripheralManagerConnectionLatencyHigh} NS_ENUM_AVAILABLE (NA, 6: 0) * /-(void) setDesiredConnectionLatency: (CBPeripheralManagerConnectionLatency) latency forCentral: (CBCentral *) central;// add a service-(void) addService: (CBMutableService *) service;// remove a service-(void) removeService: (CBMutableService *) service;// remove all services-(void) removeAllServices;// respond to read and write requests from central devices-(void) respondToRequest: (CBATTRequest *) request withResult: (CBATTError) result / / Update the subscription feature value of a connection center device-(BOOL) updateValue: (NSData *) value forCharacteristic: (CBMutableCharacteristic *) characteristic onSubscribedCentrals: (nullable NSArray *) centrals

The relevant methods of peripheral agents are as follows:

/ / this method must be implemented after the status is available, you can send a broadcast-(void) peripheralManagerDidUpdateState: (CBPeripheralManager *) peripheral;// connection reply using a method similar to centralManager-(void) peripheralManager: (CBPeripheralManager *) peripheral willRestoreState: (NSDictionary *) method called when dict;// starts sending a broadcast-(void) peripheralManagerDidStartAdvertising: (CBPeripheralManager *) peripheral error: (nullable NSError *) error / / add callback for service invocation-(void) peripheralManager: (CBPeripheralManager *) peripheral didAddService: (CBService *) service error: (nullable NSError *) error;// method called when a central device subscribes to an eigenvalue-(void) peripheralManager: (CBPeripheralManager *) peripheral central: (CBCentral *) central didSubscribeToCharacteristic: (CBCharacteristic *) characteristic;// called when unsubscribing to an eigenvalue-(void) peripheralManager: (CBPeripheralManager *) peripheral central: (CBCentral *) central didUnsubscribeFromCharacteristic: (CBCharacteristic *) characteristic / / method triggered when a read request is received-(void) peripheralManager: (CBPeripheralManager *) peripheral didReceiveReadRequest: (CBATTRequest *) method triggered when request;// receives a write request-(void) peripheralManager: (CBPeripheralManager *) peripheral didReceiveWriteRequests: (NSArray *) method called when the requests;// peripheral is ready to update the characteristic value-(void) peripheralManagerIsReadyToUpdateSubscribers: (CBPeripheralManager *) peripheral

4. CBCentral and CBPeripheral for central equipment and peripherals

The central equipment management class and the peripheral management class are introduced above, these classes are used to establish the device connection, and the data exchange service and some information of the apparatus are in the corresponding device object.

1. CBCentral attributes and methods of central equipment

/ / device UUID@property (readonly, nonatomic) NSUUID * maximum data length received by identifier;// central device @ property (readonly, nonatomic) NSUInteger maximumUpdateValueLength

2. Attributes and methods of peripheral CAPeripheral

The peripheral object is much more complex than the central object. When the centralManager is connected to the peripheral, you need to exchange data through the proxy method of the peripheral object. The main method attributes are as follows:

/ / set proxy @ property (assign, nonatomic, nullable) id delegate;// peripherals name@property (retain, readonly, nullable) NSString * name;// signal strength @ property (retain, readonly, nullable) NSNumber * RSSI NS_DEPRECATED (NA, NA, 5: 0, 8: 0) / / Peripheral status / * typedef NS_ENUM (NSInteger, CBPeripheralState) {CBPeripheralStateDisconnected = 0SCH / unconnected CBPeripheralStateConnecting,// is linking CBPeripheralStateConnected,// has connected CBPeripheralStateDisconnecting NS_AVAILABLE (NA, 9x0), / / is disconnecting} NS_AVAILABLE (NA, 7500); * / @ property (readonly) CBPeripheralState state;// all services array @ property (retain, readonly, nullable) NSArray * services / / get current signal strength-(void) readRSSI;// find service objects based on service UUID-(void) discoverServices: (nullable NSArray *) serviceUUIDs;// look for specific services in the UUID array of service objects-(void) discoverIncludedServices: (nullable NSArray *) includedServiceUUIDs forService: (CBService *) service;// look for eigenvalues in a service-(void) discoverCharacteristics: (nullable NSArray *) characteristicUUIDs forService: (CBService *) service / / read data from a feature-(void) readValueForCharacteristic: (CBCharacteristic *) the maximum length of characteristic;// write data / / type is enumerated as follows / * typedef NS_ENUM (NSInteger, CBCharacteristicWriteType) {CBCharacteristicWriteWithResponse = 0 CBCharacteristicWriteWithoutResponse,// write data and receive successful receipt CBCharacteristicWriteWithoutResponse,// write data does not receive receipt}; * /-(NSUInteger) maximumWriteValueLengthForType: (CBCharacteristicWriteType) type NS_AVAILABLE (NA, 9) / / write data to a feature-(void) writeValue: (NSData *) data forCharacteristic: (CBCharacteristic *) characteristic type: (CBCharacteristicWriteType) type;// set monitoring notification for established eigenvalues-(void) setNotifyValue: (BOOL) enabled forCharacteristic: (CBCharacteristic *) characteristic;// find the description of eigenvalues-(void) discoverDescriptorsForCharacteristic: (CBCharacteristic *) characteristic;// read the description value of the feature-(void) readValueForDescriptor: (CBDescriptor *) descriptor / / description value of the write feature-(void) writeValue: (NSData *) data forDescriptor: (CBDescriptor *) descriptor

The proxy methods of peripherals are as follows:

/ / method of callback when peripheral name is changed-(void) peripheralDidUpdateName: (CBPeripheral *) peripheral NS_AVAILABLE (NA, 6: 0); / / method of callback when peripheral service changes-(void) peripheral: (CBPeripheral *) peripheral didModifyServices: (NSArray *) invalidatedServices NS_AVAILABLE (NA, 7: 0); / / method called when signal strength changes-(void) peripheralDidUpdateRSSI: (CBPeripheral *) peripheral error: (nullable NSError *) error NS_DEPRECATED (NA, NA, 5: 0,8: 0) / / method for reading signal strength callback-(void) peripheral: (CBPeripheral *) peripheral didReadRSSI: (NSNumber *) RSSI error: (nullable NSError *) error NS_AVAILABLE (NA, 8x0); / / method called when discovering a service-(void) peripheral: (CBPeripheral *) peripheral didDiscoverServices: (nullable NSError *) error;// method for discovering sub-service callbacks in the service-(void) peripheral: (CBPeripheral *) peripheral didDiscoverIncludedServicesForService: (CBService *) service error: (nullable NSError *) error / / callback method after discovering the eigenvalue of the service-(void) peripheral: (CBPeripheral *) peripheral didDiscoverCharacteristicsForService: (CBService *) service error: (nullable NSError *) callback when the eigenvalue is updated-(void) peripheral: (CBPeripheral *) peripheral didUpdateValueForCharacteristic: (CBCharacteristic *) characteristic error: (nullable NSError *) error;// callback method when writing data to the eigenvalue-(void) peripheral: (CBPeripheral *) peripheral didWriteValueForCharacteristic: (CBCharacteristic *) characteristic error: (nullable NSError *) error / / method triggered when the notification setting of eigenvalues changes-(void) peripheral: (CBPeripheral *) peripheral didUpdateNotificationStateForCharacteristic: (CBCharacteristic *) characteristic error: (nullable NSError *) error; / / method for finding descriptive information of eigenvalues-(void) peripheral: (CBPeripheral *) peripheral didDiscoverDescriptorsForCharacteristic: (CBCharacteristic *) characteristic error: (nullable NSError *) error / / method triggered when the description value of a feature is updated-(void) peripheral: (CBPeripheral *) peripheral didUpdateValueForDescriptor: (CBDescriptor *) descriptor error: (nullable NSError *) error; / / method triggered when writing description information-(void) peripheral: (CBPeripheral *) peripheral didWriteValueForDescriptor: (CBDescriptor *) descriptor error: (nullable NSError *) error

5. Service object CBService

The service object is used to manage some data services provided by peripherals, with the following attributes:

/ / whether the corresponding peripheral @ property (assign, readonly, nonatomic) CBPeripheral * peripheral;// is the eigenvalue @ property (retain, readonly, nullable) NSArray * characteristics in the self-service @ property (retain, readonly, nullable) NSArray * includedServices;// service included in the elementary service @ property (readonly, nonatomic) BOOL isPrimary;//.

6. The eigenvalue CBCharacteristic of the service

Read and write data by binding the characteristic values in the service, where the attributes are as follows:

/ / corresponding service object @ property (assign, readonly, nonatomic) CBService * service / / the attribute enumeration of eigenvalues is as follows / * typedef NS_OPTIONS (NSUInteger, CBCharacteristicProperties) {CBCharacteristicPropertyBroadcast,// allows broadcast feature CBCharacteristicPropertyRead,// readable attribute CBCharacteristicPropertyWriteWithoutResponse,// to write and receive receipt CBCharacteristicPropertyWrite,// writable attribute CBCharacteristicPropertyNotify,// notifies attribute CBCharacteristicPropertyIndicate,// to display eigenvalues CBCharacteristicPropertyAuthenticatedSignedWrites,// allows signature eigenvalues to be written to CBCharacteristicPropertyExtendedProperties, CBCharacteristicPropertyNotifyEncryptionRequired, CBCharacteristicPropertyIndicateEncryptionRequired} * / @ property (readonly, nonatomic) CBCharacteristicProperties properties;// eigenvalue data @ property (retain, readonly, nullable) NSData * value;// eigenvalue description @ property (retain, readonly, nullable) NSArray * descriptors;// is the feature of the current broadcast @ property (readonly) BOOL isBroadcasted;// is the feature being notified @ property (readonly) BOOL isNotifying

7. Read and write request object CBATTRequest

The service object is the relevant data service provided by the peripheral to the central device. After obtaining the corresponding service, the central device can make read and write requests. The attributes of the read and write object are as follows:

/ / the eigenvalue @ property (readonly, nonatomic) CBCharacteristic * characteristic;// corresponding to the central device @ property (readonly, nonatomic) CBCentral * central;// @ property (readwrite, copy, nullable) NSData * value The answer to the question about the core method of iOS Bluetooth development CoreBlueTooth library is shared here. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report