iOS Learning Bluetooth 4.0

Source: Internet
Author: User

Reprint please indicate the source

Author: Pony


iOS has been learning for a while, so it's time to do some dry work. Some time ago to study the iOS Bluetooth communication related things, the study of one of the results for everyone to share.

A project background

A brief introduction to what is being done, the device is a financial card reader that communicates with the iphone via Bluetooth. Mobile app by sending different instructions (via Bluetooth) to control the card reader to perform some actions, such as reading magnetic stripe card, read the financial IC card and so on. The last few pictures are easy to understand:



Look at the above pictures, you should probably know what this is.

Two IOS bluetooth introduction

The Bluetooth protocol itself has undergone an upgrade from 1.0 to 4.0, and the latest 4.0 is known for its low power consumption, so it is generally called ble (bluetoothlow Energy).

IOS has two frames that support Bluetooth connectivity to peripherals. One is externalaccessory. From ios3.0 began to support, but also before the iphone4s out of a more than a model, but it has a bad place, External accessory need to get Apple's MFI certification.

Another framework is the Corebluetooth that this article describes, which is supported in Iphone4s and is designed to communicate with BLE devices (because its APIs are based on BLE). This does not require MFI, and now many Bluetooth devices support 4.0, so it is also a recommended development method in iOS.

Three Corebluetooth Introduction

The core of the Corebluetooth framework is actually two things, peripheral and central, which can be understood as peripherals and centers. They each have a set of related APIs and classes, as shown in:

If the device you want to program is central then you use most of it, and vice versa. In our example, the financial card reader is peripheral, our iphone is central, so I will mostly use the class in the left part. There are many examples of programming using peripheral, such as using an ipad and an iphone to communicate, the ipad can be thought of as the central,iphone end is peripheral, in this case on the iphone will use the right part of the class to develop.

Four services and features

There is a concept that needs to be explained first. What are services and features (service and characteristic)?

Each Bluetooth 4.0 device is displayed by service and feature, and one device must contain one or more services, each of which contains several features. A feature is the smallest unit of interaction with the outside world. For example, a Bluetooth 4.0 device, with feature a to describe their factory information, with feature B to send and receive data and so on.

Services and features are uniquely identified with UUID, the concept of UUID if not clear, please Google, the International Bluetooth organization for some very typical equipment (such as measuring heartbeat and blood pressure devices) set a standard service UUID (the characteristics of the UUID more, not listed here), as follows :

 #define Ble_uuid_alert_notification_service 0x1811 #define Ble_uuid_battery_service 0x180f #define Ble_u Uid_blood_pressure_service 0x1810 #define Ble_uuid_current_time_service 0x1805 #define Ble_uuid_cycling_speed_ And_cadence 0x1816 #define Ble_uuid_device_information_service 0x180a #define Ble_uuid_glucose_service 0x180 8 #define Ble_uuid_health_thermometer_service 0x1809 #define Ble_uuid_heart_rate_service 0x180d #define BL E_uuid_human_interface_device_service 0x1812 #define Ble_uuid_immediate_alert_service 0x1802 #define BLE_UUID_ Link_loss_service 0x1803 #define Ble_uuid_next_dst_change_service 0x1807 #define Ble_uuid_phone_alert_status_s    Ervice 0x180e #define Ble_uuid_reference_time_update_service 0x1806 #define Ble_uuid_running_speed_and_cadence     0x1814 #define Ble_uuid_scan_parameters_service 0x1813 #define Ble_uuid_tx_power_service 0x1804 #define   Ble_uuid_cgm_service0x181a 


Of course there are a lot of devices that are not in this standard list, like the one I used for this financial card reader. Bluetooth device hardware vendors often provide services (service) and feature (characteristics) features within their devices, such as what is used to interact (read and write), what gets module information (read-only), and so on.

Five Implementation Details

As a center to achieve complete communication, generally through the following steps:

Establish central role-scan peripherals (Discover)-connect peripherals (Connect)-scan services and features in peripherals (discover)-interact with peripherals (explore and interact)-disconnect (disconnect).

1 establishing a central role

First in my own class header file to contain Corebluetooth header file, and inherit two protocol <cbcentralmanagerdelegate,cbperipheraldelegate>, the code is as follows:

#import <corebluetooth/corebluetooth.h>cbcentralmanager *manager;manager = [[Cbcentralmanager alloc] Initwithdelegate:self Queue:nil];


2 Scanning Peripherals (Discover)


The code is as follows:

[Manager Scanforperipheralswithservices:nil Options:options];


This parameter should also be able to specify a specific peripheral uuid, then theoretically this central will only discover this particular device, but my actual test found that if you use a specific UUID parameter can not find any device , I use the following code:

Nsarray *uuidarray = [Nsarray arraywithobjects:[cbuuid uuidwithstring:@ "1800"],[cbuuid UUIDWithString:@ "180A"],[ Cbuuid uuidwithstring:@ "1cb2d155-33a0-ec21-6011-cd4b50710777"],[cbuuid uuidwithstring:@ " 6765d311-dd4c-9c14-74e1-a431bbfd0652 "],nil";     [Manager Scanforperipheralswithservices:uuidarray Options:options];

It is unclear why, the suspicion and the device itself in the broadcast packet.

3 Connecting peripherals (Connect)

When the device is scanned to 4.0, the system will tell us the device's information through the callback function, then we can connect the corresponding device, the code is as follows:

-(void) Centralmanager: (Cbcentralmanager *) Central diddiscoverperipheral: (cbperipheral *) Peripheral Advertisementdata: (nsdictionary *) advertisementdata RSSI: (NSNumber *) rssi{    if (![ _dicoveredperipherals containsobject:peripheral])        [_dicoveredperipherals addobject:peripheral];        NSLog (@ "dicoveredperipherals:%@", _dicoveredperipherals);}


Connect the specified device-(BOOL) Connect: (cbperipheral *) peripheral{    NSLog (@ "connect start");    _testperipheral = nil;        [Manager connectperipheral:peripheral                       options:[nsdictionary dictionarywithobject:[nsnumber NumberWithBool:YES ] [Forkey:cbconnectperipheraloptionnotifyondisconnectionkey]];        A timer is opened to monitor the connection timeout situation    Connecttimer = [Nstimer scheduledtimerwithtimeinterval:5.0f target:self selector: @selector ( ConnectTimeout:) userinfo:peripheral Repeats:no];    return (YES);}

4 Scanning for services and features in peripherals (Discover)

Similarly, when the connection succeeds, the system will tell us through the callback function, and then we will scan all the services and features under the device in this callback, the code is as follows:

-(void) Centralmanager: (Cbcentralmanager *) Central didconnectperipheral: (cbperipheral *) peripheral{    [ Connecttimer invalidate];//Stop Clock        NSLog (@ "Did connect to peripheral:%@", peripheral);    _testperipheral = peripheral;        [Peripheral setdelegate:self];    [Peripheral discoverservices:nil];        }

The service and characteristics of a device tend to be more, in most cases we just care about a few of them, so generally in the Discovery service and feature callbacks to match our concerns, such as the following code:

-(void) Peripheral: (cbperipheral *) Peripheral diddiscoverservices: (Nserror *) error{        NSLog (@ " Diddiscoverservices ");        if (Error)    {        NSLog (@ "discovered services for%@ with error:%@", Peripheral.name, [Error localizeddescription]);                if ([Self.delegate respondstoselector: @selector (DidNotifyFailConnectService:withPeripheral:error:)])            [ Self.delegate Didnotifyfailconnectservice:nil Withperipheral:nil Error:nil];                return;    }        For (Cbservice *service in peripheral.services)    {                if ([Service. UUID Isequal:[cbuuid Uuidwithstring:uuidstr_issc_proprietary_service]]        {            NSLog (@ "SERVICE found with UUID :%@ ", service. UUID);            [Peripheral Discovercharacteristics:nil Forservice:service];            isVPOS3356 = YES;            Break;}}}                    

-(void) Peripheral: (cbperipheral *) Peripheral Diddiscovercharacteristicsforservice: (Cbservice *) Service error: ( Nserror *) Error {if (error) {NSLog (@ "discovered characteristics for%@ with error:%@", service.                UUID, [Error localizeddescription]); if ([Self.delegate respondstoselector: @selector (DidNotifyFailConnectChar:withPeripheral:error:)]) [Self.delegat                E didnotifyfailconnectchar:nil Withperipheral:nil Error:nil];    Return } for (Cbcharacteristic *characteristic in service.characteristics) {if ([characteristic. UUID Isequal:[cbuuid Uuidwithstring:uuidstr_issc_trans_tx]) {NSLog (@ "discovered read characteristics:% @ For service:%@ ", characteristic. UUID, service.                        UUID); _readcharacteristic = characteristic;//Save read feature if ([Self.delegate respondstoselector: @selector (DIDFO Undreadchar:)]) [Self.delegate didfoundreadchar:characteristic];        Break }} for (cbcharacteristic * characteristic in service.characteristics) {if ([characte Ristic. UUID Isequal:[cbuuid Uuidwithstring:uuidstr_issc_trans_rx]] {NSLog (@ "discovered write characteristics: %@ for service:%@ ", characteristic. UUID, service.            UUID); _writecharacteristic = characteristic;//Save the Write feature if ([Self.delegate respondstoselector: @selector (DIDF                        Oundwritechar:)]) [Self.delegate didfoundwritechar:characteristic];                                Break }} if ([Self.delegate respondstoselector: @selector (DidFoundCharacteristic:withPeripheral:error:)]) [Self    . Delegate Didfoundcharacteristic:nil Withperipheral:nil Error:nil]; }

I believe you should have noticed that the callback function begins with "Did", and these functions are not called by you, but are automatically called after the system is reached.

5 Data interaction with peripherals (explore and interact)

Sending the data is simple, we can encapsulate a function like this:

Write data-(void) Writechar: (NSData *) data{    [_testperipheral writevalue:data forcharacteristic:_writecharacteristic Type:cbcharacteristicwritewithresponse];}


_testperipheral and _writecharacteristic are the device objects and features that we can read and write before we save.

Then we can call it outside, like of course I want to trigger the swipe, first group the packet, and then call the Send function:

-(void) msrread{        unsigned char command[512] = {0};    unsigned char *ptmp;    int nsendlen = 0;    unsigned char uccrc[3] = {0};        _commandtype = Command_msr_read;        ptmp = command;            *ptmp = 0x02;//startptmp++;    *ptmp = 0xc1;//main cmdptmp++;        *ptmp = 0x07;//sub cmdptmp++;                Nsendlen = 2;    *ptmp = Nsendlen/256;ptmp++;*ptmp = nsendlen%256;ptmp++;        *ptmp = 0x00;//sub cmdptmp++;        *ptmp = 0x00;//sub cmdptmp++;        Crc16ccitt (COMMAND+1,PTMP-COMMAND-1,UCCRC); memcpy (ptmp,uccrc,2);            NSData *data = [[NSData alloc] Initwithbytes:&command length:9];    NSLog (@ "Send data:%@", data);    [G_bleinstance.recvdata setlength:0];        [G_bleinstance Writechar:data];}


There are two types of data reading, one is direct reading (reading directly) and the other is subscription (subscribe). from the name can basically understand the difference between the two. The actual use of a specific application to see specific scenarios and characteristics of the properties themselves. What is the attribute of the characteristic itself, the first good understanding? The feature has a properties field (characteristic. Properties), which is an integer value that has the following definitions:

enum {     cbcharacteristicpropertybroadcast = 0x01,     cbcharacteristicpropertyread = 0x02,     Cbcharacteristicpropertywritewithoutresponse = 0x04,     cbcharacteristicpropertywrite = 0x08,     Cbcharacteristicpropertynotify = 0x10,     cbcharacteristicpropertyindicate = 0x20,     Cbcharacteristicpropertyauthenticatedsignedwrites = 0x40,     cbcharacteristicpropertyextendedproperties = 0x80,     };


For example, the feature you want to interact with, the value of its properties is 0x10, which means you can only receive data in the form of a subscription. I'm here to subscribe, the code to start the subscription is as follows:

Monitoring device-(void) startsubscribe{    [_testperipheral setnotifyvalue:yes forcharacteristic:_readcharacteristic];}


When the device has data returned, it is also notified by a system callback, as follows:

-(void) Peripheral: (cbperipheral *) Peripheral didupdatevalueforcharacteristic: (cbcharacteristic *) characteristic Error: (Nserror *) error{if (error) {NSLog (@ "Error updating value for characteristic%@ error:%@", Characteristic.                UUID, [Error localizeddescription]); if ([_mainmenudelegate respondstoselector: @selector (didnotifyreaderror:)]) [_mainmenudelegate Didnotifyreaderro                R:error];    Return            } [_recvdata AppendData:characteristic.value];        if ([_recvdata length] >= 5)//received length {unsigned char *buffer = (unsigned char *) [_recvdata bytes];        int nlen = buffer[3]*256 + buffer[4]; if ([_recvdata length] = = (nlen+3+2+2)) {//Receive complete, notify the agent to do things if ([_mainmenudelegate Respondstosele                    ctor: @selector (Didnotifyreaddata)]) [_mainmenudelegate Didnotifyreaddata]; }    }}


6 Disconnecting (Disconnect)

This is relatively simple, just need an API on the line, the code is as follows:

Active Disconnect device-(void) disconnect{        if (_testperipheral! = nil)    {        NSLog (@ "disConnect start");        [Manager cancelperipheralconnection:_testperipheral];}    }

Six results show


On a few, the UI is not how to modify, the main focus on functions, to achieve the reading of track information, and financial IC card APDU interaction and other functions.





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.