iOS藍(lán)牙4.0打印小票功能的實(shí)現(xiàn)

公司業(yè)務(wù)有涉及到訂單模塊永高,客戶需要連接藍(lán)牙打印機(jī)打印訂單小票嫉拐。所以本文就記錄一下iOS藍(lán)牙打印的相關(guān)知識(shí)以及實(shí)際開發(fā)中遇到的問題解決方案泼诱。

1.前言

如果需要手機(jī)連接藍(lán)牙設(shè)備就有兩種方案:1.藍(lán)牙設(shè)備生產(chǎn)廠商通過MFi認(rèn)證(藍(lán)牙軟件開發(fā)者使用蘋果標(biāo)準(zhǔn)的Bluetooth profiles可以不用申請(qǐng)MFi開發(fā)認(rèn)證)缤灵。2.藍(lán)牙芯片升級(jí)支持Bluetooth4.0(BLE)協(xié)議


image.png

以下內(nèi)容只適合藍(lán)牙4.0抗愁,如我們碰到過客戶設(shè)備藍(lán)牙版本是2.0的情況,咨詢生廠廠家技術(shù)支持后得到這樣的回復(fù)。

咨詢問題.png
官方回復(fù).png

2. 藍(lán)牙基礎(chǔ)知識(shí)

兩種模式.png

兩組API分別對(duì)應(yīng)不同的業(yè)務(wù)場景:
(1)左側(cè)的是“中心模式”,就是以你的APP作為中心追驴,連接其他的外設(shè);中心模式也是本文使用的模式疏之。
(2)右側(cè)的是“外設(shè)模式”殿雪,使用手機(jī)作為外設(shè)識(shí)別其他中心設(shè)備操作的場景。
每個(gè)藍(lán)牙4.0的設(shè)備都是通過服務(wù)和特征來展示自己的锋爪,一個(gè)設(shè)備包含一個(gè)或多個(gè)服務(wù)丙曙,每個(gè)服務(wù)下面又包含若干個(gè)特征爸业。特征是與外界交互的最小單位。

下圖展示的是藍(lán)牙打印中心模式的整體流程河泳。

image.png

3.藍(lán)牙打印開發(fā)步驟

3.1 建立藍(lán)牙管理中心角色

創(chuàng)建Central管理器時(shí)沃呢,管理器對(duì)象會(huì)調(diào)用代理對(duì)象的centralManagerDidUpdateState:方法,需要實(shí)現(xiàn)這個(gè)方法來確保本地設(shè)備支持BLE(CBCentralManagerDelegate)

#pragma  mark -CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString * state = nil;
    switch ([central state])
    {
        case CBCentralManagerStateUnsupported:
            state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
        {
            state = @"work";
            [self startDeviceDiscovery];
            break;
        }
        case CBCentralManagerStateUnknown:
        default:
            ;
    }
    NSLog(@"Central manager state: %@", state);
}

3.2 搜索可用的藍(lán)牙設(shè)備外設(shè)

調(diào)用CBCentralManager的scanForPeripheralsWithServices方法來掃描周圍正在發(fā)出廣播的外設(shè)拆挥。每找到一個(gè)外設(shè)會(huì)調(diào)centralManager:didDiscoverPeripheral:advertisementData:RSSI: 方法薄霜。該方法會(huì)CBPeripheral返回找到的外設(shè),所以可以使用數(shù)組將找到的外設(shè)保存纸兔。

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if (peripheral)
    {
        NSLog(@"foundDevice. name[%s],RSSI[%d]\n",peripheral.name.UTF8String,peripheral.RSSI.intValue);
        {
            //self.peripheral = peripheral;
            //發(fā)現(xiàn)設(shè)備后即可連接該設(shè)備 調(diào)用完該方法后會(huì)調(diào)用代理CBCentralManagerDelegate的- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral表示連接上了設(shè)別
            //如果不能連接會(huì)調(diào)用 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
            //[centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnConnectionKey : YES}];
            if (![self.deviceList containsObject:peripheral])
                [self.deviceList  addObject:peripheral];
            
            [_reDiscoveryView removeFromSuperview];
            
            [self.deviceListTableView reloadData];
        }
    }
}

3.3連接藍(lán)牙外設(shè)

當(dāng)連接成功后惰瓜,會(huì)回調(diào)方法centralManager:didConnectPeripheral:。在這個(gè)方法中汉矿,可以去記錄當(dāng)前的連接狀態(tài)等數(shù)據(jù)崎坊。

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"has connected");
    peripheral.delegate = self;
    [[CentralManager sharedInstance].connectedDeviceArr addObject:peripheral];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self.deviceList indexOfObject:peripheral] inSection:0];
    BluetoothDeviceCell * cell = [self.deviceListTableView cellForRowAtIndexPath:indexPath];
    cell.connectedStatus = YES;
    
    //此時(shí)設(shè)備已經(jīng)連接上了找到該設(shè)備上的指定服務(wù) 調(diào)用完該方法后會(huì)調(diào)用代理CBPeripheralDelegate(現(xiàn)在開始調(diào)用另一個(gè)代理的方法了)的
    //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    
    for (CBPeripheral *aPeripheral in [CentralManager sharedInstance].connectedDeviceArr) {
        [aPeripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];
        
        [aPeripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID_cj]]];
    }
}

如果連接失敗,則會(huì)調(diào)用:

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    //連接發(fā)生錯(cuò)誤
    NSLog(@"connected periphheral failed");
}

3.4掃描外設(shè)服務(wù)和特征

image.png

當(dāng)與外設(shè)成功建立連接以后洲拇,就可以通信了奈揍。第一步是先找到當(dāng)前外設(shè)提供的 service。調(diào)用CBPeripheralDelegatel的discoverServices:方法可以找到當(dāng)前外設(shè)的所有 service赋续。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error==nil)
    {
        //在這個(gè)方法中要查找到需要的服務(wù)  然后調(diào)用discoverCharacteristics方法查找需要的特性
        //該discoverCharacteristics方法調(diào)用完后會(huì)調(diào)用代理CBPeripheralDelegate的
        //- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        for (CBService *service in peripheral.services)
        {
            if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]])
            {
                [CentralManager sharedInstance].cjFlag=0;
                //[peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
                [peripheral discoverCharacteristics:nil forService:service];
            }
            else if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID_cj]])
            {
                //[peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
                [CentralManager sharedInstance].cjFlag=1;
                [peripheral discoverCharacteristics:nil forService:service];
            }
        }
    }
}

在上面的方法中查找到需要的服務(wù)男翰,然后調(diào)用discoverCharacteristics方法查找需要的特性:

- (void)discoverCharacteristics:(nullable NSArray<CBUUID *> *)characteristicUUIDs forService:(CBService *)service;

上述方法調(diào)用完后會(huì)調(diào)用代理方法didDiscoverCharacteristicsForService

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在這個(gè)方法中要找到我們所需的服務(wù)的特性 然后調(diào)用setNotifyValue方法告知我們要監(jiān)測這個(gè)服務(wù)特性的狀態(tài)變化
        //當(dāng)setNotifyValue方法調(diào)用后調(diào)用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        for (CBCharacteristic *characteristic in service.characteristics)
        {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kWriteCharacteristicUUID]])
            {
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                [CentralManager sharedInstance].activeWriteCharacteristic = characteristic;
            }
            else
                if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kReadCharacteristicUUID]])
                {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    [CentralManager sharedInstance].activeReadCharacteristic = characteristic;
                }
                else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kFlowControlCharacteristicUUID]]) {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    [CentralManager sharedInstance].activeFlowControlCharacteristic = characteristic;
                    [CentralManager sharedInstance].credit = 0;
                    [CentralManager sharedInstance].response = 1;
                }
                else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kWriteCharacteristicUUID_cj]]) {
                    
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    [CentralManager sharedInstance].activeWriteCharacteristic = characteristic;
                }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kReadCharacteristicUUID_cj]]) {
                    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                    [CentralManager sharedInstance].activeReadCharacteristic = characteristic;
                }
            [self.deviceListTableView reloadData];
            [self.scanConnectActivityInd stopAnimating];
            self.tempActiveDevice = peripheral;
        }
    }
}

3.5 與外設(shè)進(jìn)行數(shù)據(jù)交互

1)read方法時(shí),回調(diào)updataValue纽乱;nofify時(shí)蛾绎,notification回調(diào)一次后,updataValue再開始調(diào)鸦列,且不只一次租冠;
2)接收 characteristic 數(shù)據(jù)的方式有兩種:
在需要接收數(shù)據(jù)的時(shí)候,調(diào)用 readValueForCharacteristic:薯嗤,這種是需要主動(dòng)去接收的顽爹。
用 setNotifyValue:forCharacteristic: 方法訂閱,當(dāng)有數(shù)據(jù)發(fā)送時(shí)骆姐,可以直接在回調(diào)中接收镜粤。
向 characteristic 寫數(shù)據(jù)
寫數(shù)據(jù)其實(shí)是一個(gè)很常見的需求,如果 characteristic 可寫诲锹,你可以通過CBPeripheral類的writeValue:forCharacteristic:type:方法來向設(shè)備寫入NSData數(shù)據(jù)。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error==nil) {
        //在這個(gè)方法中要找到我們所需的服務(wù)的特性 然后調(diào)用setNotifyValue方法告知我們要監(jiān)測這個(gè)服務(wù)特性的狀態(tài)變化
        //當(dāng)setNotifyValue方法調(diào)用后調(diào)用代理CBPeripheralDelegate的- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
         ......
}
 [[CentralManager sharedInstance].activeDevice writeValue:[NSData dataWithBytes:buf length:l] forCharacteristic:[CentralManager sharedInstance].activeWriteCharacteristic type:CBCharacteristicWriteWithResponse];

3.6 斷開連接

首先調(diào)用CBCentralManager的cancelPeripheralConnection方法去斷開連接

- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;

如果成功斷開連接涉馅,調(diào)用didDisconnectPeripheral方法

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    
    [[CentralManager sharedInstance].connectedDeviceArr removeObject:peripheral];
    
    if ([[CentralManager sharedInstance].selectedDeviceList containsObject:peripheral]) {
        [[CentralManager sharedInstance].selectedDeviceList removeObject:peripheral];
    }
    
    [self.deviceListTableView reloadData];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self.deviceList indexOfObject:peripheral] inSection:0];
    BluetoothDeviceCell * cell = [self.deviceListTableView cellForRowAtIndexPath:indexPath];
    cell.connectedStatus = NO;
//    [self selectPrintDevice:cell];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末归园,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子稚矿,更是在濱河造成了極大的恐慌庸诱,老刑警劉巖捻浦,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異桥爽,居然都是意外死亡朱灿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門钠四,熙熙樓的掌柜王于貴愁眉苦臉地迎上來盗扒,“玉大人,你說我怎么就攤上這事缀去÷略睿” “怎么了?”我有些...
    開封第一講書人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵缕碎,是天一觀的道長褥影。 經(jīng)常有香客問我,道長咏雌,這世上最難降的妖魔是什么凡怎? 我笑而不...
    開封第一講書人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮赊抖,結(jié)果婚禮上统倒,老公的妹妹穿的比我還像新娘。我一直安慰自己熏迹,他們只是感情好檐薯,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著注暗,像睡著了一般坛缕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上捆昏,一...
    開封第一講書人閱讀 49,784評(píng)論 1 290
  • 那天赚楚,我揣著相機(jī)與錄音,去河邊找鬼骗卜。 笑死宠页,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的寇仓。 我是一名探鬼主播举户,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼遍烦!你這毒婦竟也來了俭嘁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤服猪,失蹤者是張志新(化名)和其女友劉穎供填,沒想到半個(gè)月后拐云,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡近她,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年叉瘩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片粘捎。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡薇缅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出晌端,到底是詐尸還是另有隱情捅暴,我是刑警寧澤,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布咧纠,位于F島的核電站蓬痒,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏漆羔。R本人自食惡果不足惜梧奢,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望演痒。 院中可真熱鬧亲轨,春花似錦、人聲如沸鸟顺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽讯嫂。三九已至蹦锋,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間欧芽,已是汗流浹背莉掂。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留千扔,地道東北人憎妙。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像曲楚,于是被迫代替她去往敵國和親厘唾。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容