Ios_sn_bluetooth (ii) Code implementation of IOS connection peripherals

Source: Internet
Author: User

Original: Http://www.cocoachina.com/ios/20150917/13456.html?utm_source=tuicool&utm_medium=referral

The previous article introduced the technical knowledge of Bluetooth, here we specify the central mode of the application scenario. The main device (mobile phone goes to scan connected peripherals, discovers peripheral services and properties, operates services and attributes of the app. In general, peripherals (Bluetooth devices, such as smart bracelet, etc.), will be developed by hardware engineers, and define the services provided by the device, each service for the characteristics of each feature (read-only, write-only, notification, etc.), the business scenario of this example is to use a mobile phone app to read and write Bluetooth devices.

Code implementation process for iOS connected peripherals

1. Establishing a central role

2. Scanning Peripherals (Discover)

3. Connecting Peripherals (Connect)

4. Scanning for services and features in peripherals (Discover)

-4.1 access to peripherals services

-4.2 Get the characteristics of the peripheral, get the value of characteristics, get the value of characteristics descriptor and descriptor

5. Data interaction with peripherals (explore and interact)

6. Notice of subscription to characteristic

7. Disconnect (disconnect)

Prepare the Environment

1 Xcode

2 Development certificate and mobile phone (Bluetooth program needs to use the use of real machine debugging, using the simulator can also be debugged, but the method is very painful, I will put in the last say)

3 Bluetooth Peripherals

Implementation steps

1 Import corebluetooth header file, establish Master device management class, set master device delegate

#import <corebluetooth corebluetooth.h= "" > @interface viewcontroller:uiviewcontroller< Cbcentralmanagerdelegate> @interface Viewcontroller () {//System Bluetooth Device Management object, he can be understood as the main device, through which he can scan and link peripherals Cbcen    Tralmanager *manager;        }-(void) viewdidload {[Super viewdidload]; /* Set the master device's delegate, Cbcentralmanagerdelegate must implement:-(void) Centralmanagerdidupdatestate: (Cbcentralm Anager *) central;//the host device state changes the delegate, in the initialization of the Cbcentralmanager is appropriate to open the device, only if the device is properly opened to use other choices to implement the delegate is more important:-(void) C Entralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: ( Nsdictionary *) Advertisementdata Rssi: (NSNumber *) Rssi; Find the peripheral's delegate-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) peripheral;// Connecting peripheral successful delegates-(void) Centralmanager: (Cbcentralmanager *) Central didfailtoconnectperipheral: (cbperipheral *) periphe RAL Error: (NSERROR *) error;//Peripheral Connection failedDelegate-(void) Centralmanager: (Cbcentralmanager *) Central diddisconnectperipheral: (cbperipheral *) Peripheral Error: (Nserror *) error;//Disconnect the delegate///Initialize and set the delegate and thread queue, preferably a thread's parameters can be nil, the default will be the main thread manager = [[Cbcentralmanag ER alloc]initwithdelegate:self queue:dispatch_get_main_queue ()];

  


2 Scanning peripheral (discover), scanning the peripheral method we placed in the Centralmanager successfully opened the delegate, because only the device successfully opened to start scanning, or will be an error.

 -(void) Centralmanagerdidupdatestate: (Cbcentralmanager *) central{switch (central.state) {case                    Cbcentralmanagerstateunknown: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/* The first parameter nil is to scan all surrounding peripherals, scan to the peripherals will enter-( void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata                     :(nsdictionary *) advertisementdata Rssi: (NSNumber *) Rssi;                     */[manager Scanforperipheralswithservices:nil Options:nil];                Break            Default:break; }}//Scan to device will enter Method-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperiphe RAL *) Peripheral Advertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{NSLog (@ "When scanning to device:%@"            , peripheral.name); Next you can connect the device}

  


3 Connecting peripherals (Connect)

Scan to device will enter Method-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral adv Ertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{//connected to our test equipment, if you do not have a device, you can download an app called LIGHTB                   Ule app to simulate a device//here to set the next connection rule, I set the P start device if ([Peripheral.name hasprefix:@ "P"]) { /* A master device can connect up to 7 peripherals, each with a maximum of one primary device connection, a successful connection, a failure, and a disconnection into its own delegate-(void) Centralmanager :(Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) peripheral;//connecting peripheral successful delegates-(void) Centra Lmanager: (Cbcentralmanager *) Central didfailtoconnectperipheral: (cbperipheral *) Peripheral Error: (NSERROR *) error;/ /Peripheral Connection failed delegate-(void) Centralmanager: (Cbcentralmanager *) Central diddisconnectperipheral: (Cbperipheral *) p Eripheral Error: (NSERROR *) error;//Disconnect Peripheral Delegate *//Connect device [Manager conn Ectperipheral:peripheral optionS:nil]; }}//Connect to peripherals-Success-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (C        Bperipheral *) Peripheral {NSLog (@ ">>> connected to device named (%@)-Success", peripheral.name); }//Connection to peripherals-failed-(void) Centralmanager: (Cbcentralmanager *) Central didfailtoconnectperipheral: (Cbperip Heral *) Peripheral Error: (NSERROR *) error {NSLog (@ ">>> connected to device with name (%@)-Failed, Reason:%@", [peripheral name        ],[error localizeddescription]); //peripherals disconnect-(void) Centralmanager: (Cbcentralmanager *) Central diddisconnectperipheral: (Cbperiphera L *) Peripheral Error: (NSERROR *) error{NSLog (@ ">>> Peripheral connection Disconnected%@:%@\n", [peripheral name], [Error Locali         Zeddescription]); }

  


4 Scanning for services and features in peripherals (Discover)

After the device is connected successfully, the service of the device can be scanned, and the same is done by the delegate form, which will enter the delegate method after scanning the result. However, this delegate is no longer a principal device delegate (Cbcentralmanagerdelegate), but rather a peripheral delegate (cbperipheraldelegate), which contains many callback methods for the main device to interact with the peripherals, including access services, Get characteristics, get characteristics values, get characteristics descriptor, and descriptor values, write data, read Rssi, subscribe to data by notification, and more.

4.1 Obtaining services for peripherals

Connect to peripherals-Success-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) periphe            RAL {NSLog (@ ">>> connected to device named (%@)-Success", peripheral.name); Set the peripheral delegate cbperipheraldelegate//@interface Viewcontroller:uiviewcontroller<cbcentralmanagerdelegat            e,cbperipheraldelegate> [Peripheral setdelegate:self]; Scan peripheral Services, Success will enter method:-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error{[per         Ipheral Discoverservices:nil];            }//Scan to services-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error{            NSLog (@ ">>> Scan to service:%@", peripheral.services); if (Error) {NSLog (@ ">>>discovered Services for%@ with error:%@", Peripheral.name, [E                Rror localizeddescription]);            Return } for (Cbservice *service in Peripheral.services) {NSLog (@ "%@", service.                             UUID); Scan the characteristics of each service, scan to enter method:-(void) Peripheral: (Cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (cbservice *) Service error: (NSERROR *) error [Peripheral D                         Iscovercharacteristics:nil Forservice:service]; }         }
4.2 Get the characteristics of the peripheral, get the value of characteristics, get the value of characteristics descriptor and descriptor//scan to characteristics-(voi d) Peripheral: (cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (Cbservice *) Service error: (NSError *) error{if (error) {NSLog (@ "error discovered characteristics for%@ with error:%@", service.u UID, [Error localizeddescription]); Return } for (Cbcharacteristic *characteristic in service.characteristics) {NSLog (@ "service:%@ Ch Aracteristic:%@ ", service. Uuid,characteristic. UUID); }//Get characteristic value, read data into method:-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: (CB Characteristic *) characteristic error: (Nserror *) error for (Cbcharacteristic *characteristic in Service.characteri Stics) {{[Peripheral readvalueforcharacteristic:characteristic]; }}//Search characteristic's DESCRIptors, read data will enter method:-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverdescriptorsforcharacteristic: ( Cbcharacteristic *) Characteristic error: (Nserror *) error for (Cbcharacteristic *characteristic in Service.characte Ristics) {[Peripheral discoverdescriptorsforcharacteristic:characteristic]; }}//Gets the value of the charateristic-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: (CBChar Acteristic *) Characteristic error: (Nserror *) error{//print out characteristic UUID and value//! Note that the type of value is NSData, and when specifically developed, it The Data NSLog (@ "characteristic uuid:%@ value:%@", characteristic) is parsed according to the method developed by the peripheral protocol. Uuid,characteristic.value); }//Search to characteristic's descriptors-(void) Peripheral: (cbperipheral *) Peripheral Diddiscoverdescriptorsforcharacteri Stic: (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); }}//Gets the value to descriptors-(void) Peripheral: (cbperipheral *) Peripheral Didupdatevaluefordescriptor: (Cbdescriptor *) Descriptor Error: (NSERROR *) error{//Print out Descriptorsuuid and value//This descriptor is a description of characteristic, usually a string, Here we convert the string to parse NSLog (@ "characteristic uuid:%@ value:%@", [NSString stringwithformat:@ "%@", descriptor. Uuid],descriptor.value); }

  


5 Write the data into the characteristic.

 Write data-(void) Writecharacteristic: (cbperipheral *) Peripheral characteristic: (cbcharacteristic *) characte Ristic value: (NSData *) value{//Print out characteristic permissions, you can see there are many kinds of, this is a ns_options, it can be used for several        Values, common have read,write,notify,indicate, know that these basic enough, before even one is read and write permission, the latter two are notifications, two different notification methods.                                              /* typedef ns_options (Nsuinteger, cbcharacteristicproperties) {Cbcharacteristicpropertybroadcast                                                   = 0x01, Cbcharacteristicpropertyread = 0x02, Cbcharacteristicpropertywritewithoutresponse = 0x04, C Bcharacteristicpropertywrite = 0x08, Cbcharacteristicpropertynoti                                               FY = 0x10, cbcharacteristicpropertyindicate = 0x20, CbcharacteristicpropertyaUthenticatedsignedwrites = 0x40, cbcharacteristicpropertyextendedproperties        = 0x80, cbcharacteristicpropertynotifyencryptionrequired ns_enum_available (NA, 6_0)          = 0x100, cbcharacteristicpropertyindicateencryptionrequired ns_enum_available (NA, 6_0) = 0x200};          */NSLog (@ "%lu", (unsigned long) characteristic.properties);            Only Characteristic.properties has write permission to write if (Characteristic.properties & Cbcharacteristicpropertywrite) {            /* Preferably a type parameter can be Cbcharacteristicwritewithresponse or type:cbcharacteristicwritewithresponse, the difference is whether there will be feedback */[Peripheral writevalue:value forcharacteristic:characteristic Type:cbcharacteristicwritewithrespo        NSE]; }else{NSLog (@ "This field is not writable!        "); }      }

  


6 Subscribe to characteristic notifications

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];    }

  


7 Disconnecting (Disconnect)

Stop scanning and disconnect    -(void) Disconnectperipheral: (Cbcentralmanager *) Centralmanager                     Peripheral: (Cbperipheral *) peripheral{        //Stop scanning        [Centralmanager Stopscan];        Disconnect        [Centralmanager cancelperipheralconnection:peripheral];    }

  

Ios_sn_bluetooth (ii) Code implementation of IOS connection peripherals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.