IOS Bluetooth Development (iii) implementation of the app as a peripheral connected (go)

Source: Internet
Author: User
<span id="Label3"></p><p><p>Reprinted from: www.cocoachina.com/ios/20151105/14071.html</p></p><p><p>Hara <span id="source">Liu Yanji</span></p></p><p><p>The last section says the app as central connection peripheral, This section describes how to use the app to publish a peripheral to other central connections</p></p><p style="text-align: center;"><p style="text-align: center;"></p></p><p><p>Still this picture, the central mode uses the left class, and the peripheral mode uses the class on the Right.</p></p><p><p><span style="color: #00b050;"><strong>Flow of peripheral mode</strong></span></p></p><p><p>1. Open peripheralmanager, Set Peripheralmanager delegate</p></p><p><p>2. Create the Characteristics,characteristics description to create the service, add characteristics to the service, and add the service to the Peripheralmanager.</p></p><p><p>3. Turn on broadcast advertising</p></p><p><p>4. Responding to Central operations</p></p><p><p>-4.1 Read Characteristics Request</p></p><p><p>-4.2 Write characteristics Request</p></p><p><p>-4.4 Subscription and unsubscribe characteristics</p></p><p><p><span style="color: #00b050;"><strong>Prepare the Environment</strong></span></p></p><p><p>1 Xcode</p></p><p><p>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), if not can use OSX program debugging</p></p><p><p>3 Bluetooth Peripherals</p></p><p><p><span style="color: #00b050;"><strong>Implementation steps</strong></span></p></p><p><p>1. Open peripheralmanager, Set Peripheralmanager delegate</p></p><p><p>Set current Viewcontroller implementation Cbperipheralmanagerdelegate delegate</p></p><pre class="brush:js;toolbar:false"><pre class="brush:js;toolbar:false">@interface Beperipheralviewcontroller:uiviewcontroller</pre></pre><p><p>Initialize Peripheralmanager</p></p><pre class="brush:js;toolbar:false"><pre class="brush:js;toolbar:false">/* similar to cbcentralmanager, Bluetooth device open takes a certain amount of time, open successfully will enter the delegate method-(void) peripheralmanagerdidupdatestate: (cbperipheralmanager *) pe     ripheral; The simulator will never get Cbperipheralmanagerstatepoweredon status */peripheralmanager = [[cbperipheralmanager alloc]initwithdelegate:se LF queue:nil];</pre></pre><p><p>2. Create the Characteristics,characteristics description, Create the service, add the characteristics to the service, and add the service to the Peripheralmanager.</p></p><p><p> In the delegate method-(void) peripheralmanagerdidupdatestate: (cbperipheralmanager *) peripheral, When the peripheral is successfully opened, Before you can configure service and Characteristics. The service and Chara objects created here are cbmutablecharacteristic and cbmutableservice. Their difference is like Nsarray and nsmutablearray. We first created characteristics and description,description is the description of characteristics, the description of a number of kinds, here is not detailed, The usual is Cbuuidcharacteristicuserdescriptionstring. </p></p><pre class="brush:js;toolbar:false">Peripheralmanager State change-  (void) peripheralmanagerdidupdatestate: (cbperipheralmanager *) peripheral{     switch  (peripheral.state)  {             //here to determine the status of Bluetooth set    when turned on can call   setup method (custom)          case CBPeripheralManagerStatePoweredOn:             nslog (@ "powered on");             [info settext:[nsstring stringwithformat:@ "device name%@ is already open and can be connected using center", localnamekey] ];            [self setup];             break;         case cbperipheralmanagerstatepoweredoff:             nslog (@ "powerEd off ");             [info settext:@" Powered off "];            break;         default:             break;    }}</pre><pre class="brush:js;toolbar:false"> //configuration bluetooch  -(void) setup{        //characteristics Field Description         cbuuid *cbuuidcharacteristicuserdescriptionstringuuid  = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];         /*          can inform the characteristic          properties:CBCharacteristicPropertyNotify          permissions CBAttributePermissionsReadable          */        cbmutablecharacteristic * Notiycharacteristic = [[cbmutablecharacteristic alloc]initwithtype:[cbuuid uuidwithstring: Notiycharacteristicuuid] properties:cbcharacteristicpropertynotify value:nil permissions: Cbattributepermissionsreadable];        /*          Readable and writable characteristics          properties:cbcharacteristicpropertywrite | cbcharacteristicpropertyread          permissions CBAttributePermissionsReadable |  cbattributepermissionswriteable         */         cbmutablecharacteristic *readwritecharacteristic = [[ cbmutablecharacteristic alloc]initwithtype:[cbuuid uuidwithstring:readwritecharacteristicuuid]  properties:cbcharacteristicpropertywrite | cbcharacteristicpropertyread value:nil  permissions:cbattributepermissionsreadable | cbattributepermissionswriteable];         //setting Description        cbmutabledescriptor *readwritecharacteristicdescription1 = [[cbmutabledescriptor alloc]initwithtype:  cbuuidcharacteristicuserdescriptionstringuuid value:@ "name"];         [readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];         /*          read-only characteristic          properties:CBCharacteristicPropertyRead          permissions CBAttributePermissionsReadable          */        cbmutablecharacteristic * Readcharacteristic = [[cbmutablecharacteristic alloc]initwithtype:[cbuuid uuidwithstring: Readcharacteristicuuid] properties:cbcharacteristicpropertyread value:nil permissions: cbattributepermissionsreadable];&Nbsp;       //service1 Initialize and add two characteristics         cbmutableservice *service1 = [[cbmutableservice alloc]initwithtype:[ cbuuid uuidwithstring:serviceuuid1] primary:yes];        [ service1 setcharacteristics:@[notiycharacteristic,readwritecharacteristic]];         //service2 initializes and joins a characteristics         cbmutableservice *service2 = [[cbmutableservice alloc]initwithtype:[cbuuid  uuidwithstring:serviceuuid2] primary:yes];        [service2  When Setcharacteristics:@[readcharacteristic]];        //is added, the agent's-  is called ( Void) peripheralmanager: (cbperipheralmanager *) peripheral didaddservice: (cbservice *) Service  error: (nserror *) error        [peripheralmanager addservice:service1];         [peripheralmanager addservice:service2]; }</pre><p><p> 3. Turn on broadcast advertising </p> </p><pre class="brush:js;toolbar:false">Perihpheral added service-  (void) peripheralmanager: (cbperipheralmanager *) peripheral  Didaddservice: (cbservice *) service error: (nserror *) error{    if  ( Error == nil)  {        serviceNum++;     }    //because we added 2 services, so we want to add it twice before sending the broadcast     if  (servicenum==2)  {        //after you add a service, you can make a notification to the outside world   call this method after calling the Agent's          //(void) peripheralmanagerdidstartadvertising: (cbperipheralmanager *) Peripheral error: (nserror *) Error        [peripheralmanager  startAdvertising:@{                                                cbadvertisementdataserviceuuidskey : @[[cbuuid  uuidwithstring:serviceuuid1],[cbuuid uuidwithstring:serviceuuid2]],                                                 CBAdvertisementDataLocalNameKey : LocalNameKey                                                }         ];    }}// Peripheral start sending advertising-  (void) peripheralmanagerdidstartadvertising: (cbperipheralmanager *) Peripheral error: (nserror *) Error{    nslog (@ "in peripheralmanagerdidstartadvertisiong");} </pre><p><p>4. Responding to Central operations</p></p><p><p>-4.1 Read Characteristics Request</p></p><p><p>-4.2 Write characteristics Request</p></p><p><p>-4.3 Subscription and unsubscribe characteristics</p></p><pre class="brush:js;toolbar:false">Subscription characteristics-(void) peripheralmanager: (cbperipheralmanager *) peripheral central: (CBCentral  *) central didsubscribetocharacteristic: (cbcharacteristic *) characteristic{     nslog (@ "subscribed to  %@ data", characteristic. UUID);     //the number of seconds per second to send a current time to the primary device     timer = [NSTimer  Scheduledtimerwithtimeinterval:1 target:self selector: @selector (senddata:)  userinfo: characteristic  repeats:yes];} Unsubscribe characteristics-(void) peripheralmanager: (cbperipheralmanager *) peripheral central: (CBCentral  *) central didunsubscribefromcharacteristic: (cbcharacteristic *) characteristic{     nslog (@ "unsubscribe  %@ data", characteristic. UUID);     //cancel Response     [timer invalidate];} Send data, the number of seconds to send the current time-(BOOL) senddata: (nstimer *) t {    cbmutablecharacteristic * Characteristic = t.userinfo;    nsdateformatter *dft = [[nsdateformatter alloc]init];     [dft setdateformat:@ "ss"];    nslog (@ "%@", [dft stringfromdate: [nsdate date]]);     //execution Response Central Notification data     return  [peripheralManager  updatevalue:[[dft stringfromdate:[nsdate date]] datausingencoding:nsutf8stringencoding]  Forcharacteristic: (cbmutablecharacteristic *) characteristic onsubscribedcentrals:nil];} Read characteristics request-  (void) peripheralmanager: (cbperipheralmanager *) peripheral  Didreceivereadrequest: (cbattrequest *) request{    nslog (@ "didReceiveReadRequest");     //determine If there is permission to read data     if  (request.characteristic.properties  & cbcharacteristicpropertyread)  {        nsdata * Data = request.characteristic.value;        [request setvalue:data];   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//A successful response to the request         [ peripheralmanager respondtorequest:request withresult:cbatterrorsuccess];    } else{        [peripheralmanager respondtorequest:request  Withresult:cbatterrorwritenotpermitted];    }}//write characteristics request-  (void) Peripheralmanager: (cbperipheralmanager *) peripheral didreceivewriterequests: (NSArray *) requests {    nslog (@ "didreceivewriterequests");     cbattrequest *request  = requests[0];    //determine If there is permission to write Data     if  ( Request.characteristic.properties & cbcharacteristicpropertywrite)  {         //needs to be converted into Cbmutablecharacteristic objects to enterLine Write Value         cbmutablecharacteristic *c = ( Cbmutablecharacteristic *) Request.characteristic;        c.value  = request.value;        [peripheralManager  respondtorequest:request withresult:cbatterrorsuccess];    }else{         [peripheralmanager respondtorequest:request withresult: cbatterrorwritenotpermitted];    }}</pre><p><p><span style="color: #00b050;"><strong>Code download:</strong></span></p></p><p><p>Most of the sample code on my blog is uploaded to GitHub with the address: https://github.com/coolnameismy/demo, click the Jump Code</p></p><p><p>The code for this document is a directory Bledemo</p></p><p><p>If you support, please follow my GitHub account, and star my project, there are other issues can be in the blog to my message blog RSS feeds</p></p><p><p></p></p><p><p>IOS Bluetooth Development (iii) implementation of the app as a peripheral connected (go)</p></p></span>

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.