A brief introduction of Bluetooth part of the basic knowledge, detailed things we can go to GitHub search Babybluetooth, there are some learning data iOS Connection peripheral procedures to establish central managers scan Peripherals Discoverperipheral Connect Peripherals connectperipheral Scan peripherals for services and features Discoverservices Discovercharacteristics
Obtain the services of the peripherals acquire the characteristics of the peripheral service to get the value of characteristic, descriptor, and the peripheral to do data interaction write, read Subscribe to characteristic notification notify disconnect disconnected implementation steps
1, the Import Corebluetooth header file, establishes the center management class, sets up the proxy
#import <CoreBluetooth/CoreBluetooth.h> @interface viewcontroller:uiviewcontroller< Cbcentralmanagerdelegate> @interface Viewcontroller () {//System Bluetooth Device Management object, you can understand the main device, through him, can go to scan and link peripherals Cbcentralmanager
*manager;
Used to save the found equipment Nsmutablearray *peripherals;
}-(void) viewdidload {[Super viewdidload]; /* Set the delegate for the master device, Cbcentralmanagerdelegate must implement:-(void) Centralmanagerdidupdatestate: (Cbcentralmanager *) central;//a delegate that changes the state of a master device, the device is turned on when the Cbcentralmanager is initialized, and only if the device is properly opened can the more important:-(void) Centralmanager: ( Cbcentralmanager *) Diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: (NSDictionary *) Advertisementdata RSSI: (NSNumber *) RSSI; Locate the peripheral's delegate-(void) Centralmanager: (Cbcentralmanager *) Didconnectperipheral: (cbperipheral *) peripheral;//connection outside Set a successful delegate-(void) Centralmanager: (Cbcentralmanager *) Didfailtoconnectperipheral: (cbperipheral *) Peripheral ER ROR: (Nserror *) error;//Peripheral Connection failed delegate
-(void) Centralmanager: (Cbcentralmanager *) Diddisconnectperipheral: (cbperipheral *) Peripheral error: (NSEr ROR *) error;//Disconnect the peripheral's delegate///Initialize and set the delegate and thread queue, preferably one thread can be a nil, the default will be the main thread manager = [[Cbcentralmanager ALLOC]INITW
Ithdelegate:self Queue:dispatch_get_main_queue ()];
2, scanning peripherals (discover), scanning peripheral methods We put in the Centralmanager successfully opened the delegate, because only the device opened successfully, can begin scanning, or will be an error.
So when reconnecting the peripherals, will not succeed, because the states has not been opened, the general write their own Bluetooth, this place to deal with, the connection of the time to judge, has not been opened to reconnect, until Poweredon
-(void) Centralmanagerdidupdatestate: (Cbcentralmanager *) central{switch (central.state) {case Cbcentr
Almanagerstateunknown:nslog (@ ">>>cbcentralmanagerstateunknown");
Break
Case Cbcentralmanagerstateresetting:nslog (@ ">>>cbcentralmanagerstateresetting");
Break
Case Cbcentralmanagerstateunsupported:nslog (@ ">>>cbcentralmanagerstateunsupported");
Break
Case Cbcentralmanagerstateunauthorized:nslog (@ ">>>cbcentralmanagerstateunauthorized");
Break
Case Cbcentralmanagerstatepoweredoff:nslog (@ ">>>cbcentralmanagerstatepoweredoff");
Break
Case Cbcentralmanagerstatepoweredon:nslog (@ ">>>cbcentralmanagerstatepoweredon"); Start Scanning Peripheral Peripherals *One parameter nil is to scan all peripheral peripherals, scan to peripherals and enter-(void) Centralmanager: (Cbcentralmanager *) Diddiscoverperiphera
L: (cbperipheral *) Peripheral Advertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) RSSI;
* * [manager Scanforperipheralswithservices:nil Options:nil];
Break
Default:break; The scan to device will enter Method-(void) Centralmanager: (Cbcentralmanager *) Diddiscoverperipheral: (Cbperipheral *) Peri Pheral advertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{NSLog (@ "When scanning to device:%@", PERIPHERAL.N
AME);
Next you can connect the device}
3, connecting peripherals
Note that the found peripheral must be held: (for example, add to an array, assign to another held variable), otherwise the Cbcentralmanager will not save the peripheral, Then the method in Cbperipheraldelegate will not be called
Scanning to the device will enter Method-(void) Centralmanager: (Cbcentralmanager *) the diddiscoverperipheral: (cbperipheral *) Peripheral AD Vertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{//Connect our test equipment, if you do not have the equipment, you can download an app called Lightbul
E's app to simulate a device//here itself to set the next connection rule, I set the device that starts with P if ([Peripheral.name hasprefix:@ "P"]) {/* A master device can have up to 7 peripherals, each peripheral can only connect to one main device, the connection succeeds, fails, and the disconnect enters the respective delegate-(void) Centralmanager: (cbcentralmanage R *) The Didconnectperipheral: (cbperipheral *) peripheral;//Connect Peripherals to a successful delegate-(void) Centralmanager: (Cbcentralm
Anager *) Didfailtoconnectperipheral: (cbperipheral *) Peripheral Error: (NSERROR *) error;//Peripheral Connection failed delegate -(void) Centralmanager: (Cbcentralmanager *) Diddisconnectperipheral: (cbperipheral *) Peripheral Error: ( Nserror *) error;//Disconnect Peripherals from the commissioned///found device must hold it, otherwise cbcentralmanager will not save peripheral, then Cbperipher
The method in Aldelegate is also not invoked. [Peripherals addobject:peripheral];
Connect device [manager connectperipheral:peripheral Options:nil]; }//Connect to peripherals-Success-(void) Centralmanager: (Cbcentralmanager *) Didconnectperipheral: (Cbperipher
Al *) Peripheral {NSLog (@ ">>> connected to name (%@) device-Success", peripheral.name); }//Connect to peripherals-failure-(void) Centralmanager: (Cbcentralmanager *) Didfailtoconnectperipheral: (cbperipheral * Peripheral Error: (NSERROR *) error {NSLog (@ >>> connected to device with name (%@)-Failed, Cause:%@ ", [Peripheral Name],[error Loc
Alizeddescription]); //peripherals disconnect-(void) Centralmanager: (Cbcentralmanager *) Diddisconnectperipheral: (cbperipheral *) PE Ripheral Error: (Nserror *) error{NSLog (@ ">>> Peripheral connection Disconnected%@:%@\n", [peripheral name], [Error LOCALIZEDDESCRI
Ption]);
}
4, scanning peripherals in the service and characteristics (discover)
After the device connection is successful, the service of the device can be scanned, and the same is done by the delegate form, and the result will go into the delegate method. But this delegate is no longer the principal device's delegate (Cbcentralmanagerdelegate), but the peripheral's delegate (Cbperipheraldelegate), which contains many callback methods for the main device interacting with the peripherals, including access to services, Get characteristics, get characteristics values, get characteristics descriptor, and descriptor values, write data, read Rssi, subscribe to data by notification, and so on.
5, access to peripherals services
Connect to peripherals-Success-(void) Centralmanager: (Cbcentralmanager *) Didconnectperipheral: (cbperipheral *) periph
eral {NSLog (@ ">>> connected to name (%@) device-Success", peripheral.name); Set peripheral delegate cbperipheraldelegate//@interface Viewcontroller:uiviewcontroller<cbcentralmanagerdelegate,c
bperipheraldelegate> [Peripheral setdelegate:self]; Scan Peripherals Services and enter method:-(void after success peripheral: (Cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error{[periph
eral Discoverservices:nil]; //Scan to services-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error{//NS
Log (@ ">>> Scan to service:%@", peripheral.services); if (Error) {NSLog (@ ">>>discovered Services for%@ with error:%@", Peripheral.name, [Error L
Ocalizeddescription]);
Return For (Cbservice *service in peripheral.services) {NSLog (@)%@ ", service.
UUID); Scan the characteristics of each service, scan to enter the method:-(void) Peripheral: (Cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (cbservice *) Service error: (NSERROR *) error [Peripheral disc
Overcharacteristics:nil Forservice:service];
}
}
6, get the characteristics of the peripheral, get the value of characteristics, get characteristics descriptor and Descriptor value
Scan to characteristics-(void) Peripheral: (cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (CBService *) Service error: (NSERROR *) error{if (error) {NSLog (@ "error discovered characteristics for%@ with err Or:%@, service.
UUID, [Error localizeddescription]);
Return For (cbcharacteristic *characteristic in service.characteristics) {NSLog (@) service:%@ Tic:%@ ", service. Uuid,characteristic.
UUID); //Gets the value of the characteristic, reads the data into the method:-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: ( Cbcharacteristic *) Characteristic error: (Nserror *) error for (Cbcharacteristic *characteristic in Service.characteris
Tics) {{[Peripheral readvalueforcharacteristic:characteristic]; }///Search characteristic descriptors, read data will enter method:-(void) Peripheral: (cbperipheral *) Peripheral Diddiscoverdescriptor Sforcharacteristic: (cbcharacteristic *) characteristic ERror: (Nserror *) error for (cbcharacteristic *characteristic in service.characteristics) {[Peripheral Discove
Rdescriptorsforcharacteristic:characteristic]; }///Get charateristic value-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: ( Cbcharacteristic *) Characteristic error: (Nserror *) error{//print out characteristic UUID and value//! Note that the type of value is NSData, when specifically developed, it will To resolve Data NSLog (@ "characteristic uuid:%@ value:%@", characteristic) according to the method of peripheral protocol.
Uuid,characteristic.value); }//Search to characteristic descriptors-(void) Peripheral: (Cbperipheral *) Peripheral Diddiscoverdescriptorsforcharacteristic: (cbcharacteristic *) characteristic error: (Nserror *) error{// Print out characteristic and his descriptors NSLog (@ "characteristic uuid:%@", characteristic.
UUID);
For (Cbdescriptor *d in characteristic.descriptors) {NSLog (@ "Descriptor uuid:%@", d.uuid); }//Get to descriptors value-(void) Peripheral: (cbperipheral *) Peripheral didupdatevaluefordescriptor: (CBDESCRIPtor *) Descriptor Error: (NSERROR *) error{//Print out Descriptorsuuid and value//This descriptor are all descriptions of characteristic, usually strings, So here we convert the string to parse NSLog (@ "characteristic uuid:%@ value:%@", NSString stringwithformat:@ "%@", descriptor.
Uuid],descriptor.value);
}
7, write data to characteristic
Write data-(void) Writecharacteristic: (cbperipheral *) Peripheral characteristic: (cbcharacteristic *) characteristic Value: (NSData *) value{//Print out characteristic permissions, you can see that there are many kinds, this is a ns_options, it can be used for several values, common have READ,WR
Ite,notify,indicate, know that these few basic enough, the former is read and write permission, the latter two are notifications, two different means of notification. /* typedef ns_options (Nsuinteger, cbcharacteristicproperties) {Cbcharacteristicpropertybroadcast = 0x01, Cbcharacteristicpropertyread = 0x02, Cbcharacteristicpropertywritewithoutresponse = 0x04, cbcharacteristic Propertywrite = 0x08, cbcharacteristicpropertynotify = 0x10, cbcharacteristicpropertyindicate = 0x20, cbcharacteristicpropertyauthenticatedsignedwrites = 0x40, cbcharacteristicpropertyextendedproperties = 0x80, CBC Haracteristicpropertynotifyencryptionrequired ns_enum_available (NA, 6_0) = 0x100, Cbcharacteristicpropertyindi
Cateencryptionrequired ns_enum_available (NA, 6_0) = 0x200};
* * NSLOG (@ "%lu", (unsigned long) characteristic.properties);
Only characteristic.properties with write permission to write if (Characteristic.properties & Cbcharacteristicpropertywrite) { /* Best one type parameter can be Cbcharacteristicwritewithresponse or type:cbcharacteristicwritewithresponse, the difference is whether there will be feedback *
/[Peripheral writevalue:value forcharacteristic:characteristic Type:cbcharacteristicwritewithresponse]; }else{NSLog (@) This field is not writable.
");
}
}
8, subscribe to the characteristic notice
Generally in the discovercharacteristic agent, found the type is notify characteristic, directly can subscribe to the
Set notification
-(void) Notifycharacteristic: (cbperipheral *) Peripheral
characteristic: (cbcharacteristic *) characteristic{
//Set notification, data notification will enter: Didupdatevalueforcharacteristic method
[Peripheral Setnotifyvalue:yes Forcharacteristic:characteristic];
}
Cancellation Notification
-(void) Cancelnotifycharacteristic: (cbperipheral *) Peripheral
characteristic: (cbcharacteristic *) characteristic{
[Peripheral setnotifyvalue:no forcharacteristic:characteristic];
}
9, disconnect (disconnect)
Stop scanning and disconnecting
-(void) Disconnectperipheral: (Cbcentralmanager *) Centralmanager
Peripheral: (Cbperipheral *) peripheral{
//Stop scanning
[Centralmanager Stopscan];
Disconnect
[Centralmanager cancelperipheralconnection:peripheral];
}
Bluetooth module OTA upgrade in iOS (Ymodem protocol)
See next article