公司業(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ù)。
2. 藍(lán)牙基礎(chǔ)知識(shí)
兩組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)牙打印中心模式的整體流程河泳。
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ù)和特征
當(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];
}