第一步:
//
// PluginTest.m
// HBuilder-Hello
//
// Created by Mac Pro on 14-9-3.
// Copyright (c) 2014年 DCloud. All rights reserved.
//
import "BluePrinter.h"
import "PDRCoreAppFrame.h"
import "H5WEEngineExport.h"
import "PDRToolSystemEx.h"
import "WebViewForImage.h"
// 扩展插件中需要引入需要的系统库
import <LocalAuthentication/LocalAuthentication.h>
@implementation BluePrinter
// 扫描方法 返回对象包含索引 名称 uuid等
-
(void)Scanning:(PGMethod*)commands{
if(commands){
// 回调id NSString* cbId = [commands.arguments objectAtIndex:0]; SEPrinterManager *_manager = [SEPrinterManager sharedInstance]; [_manager startScanPerpheralTimeout:10 Success:^(NSArray<CBPeripheral *> *perpherals,BOOL isTimeout) { @try { NSUInteger pcount = [perpherals count]; NSMutableArray *temp = [NSMutableArray array]; for (NSUInteger i = 0; i < pcount; i++) { // 转化Integer为String NSString *index = [[NSString alloc] initWithFormat:@"%lu",(unsigned long)i]; // 转化uuid为String NSString *uuid = [[NSString alloc] initWithFormat:@"%@",perpherals[i].identifier]; // 组成字典结构 NSDictionary *device = @{@"index":index,@"name":perpherals[i].name,@"uuid":uuid}; // 放入数组 [temp addObject:device]; } self.deviceArray = perpherals; PDRPluginResult * result = [PDRPluginResult resultWithStatus:PDRCommandStatusOK messageAsArray:temp]; result.keepCallback = true; NSLog(@"扫描中:"); [self toCallback:cbId withReslut:[result toJSONString]]; } @catch (NSException *exception) { // 异常停止搜索 [_manager stopScan]; } } failure:^(SEScanError error) { NSLog(@"error:%ld",(long)error); }];
}
}
@end
第二步:
//
// SEPrinterManager.m
// SEBLEPrinter
//
// Created by Harvey on 16/5/5.
// Copyright © 2016年 Halley. All rights reserved.
//
import "SEPrinterManager.h"
define kSECharacter @"character"
define kSEType @"type"
// 发送数据时,需要分段的长度,部分打印机一次发送数据过长就会乱码,需要分段发送。这个长度值不同的打印机可能不一样,你需要调试设置一个合适的值(最好是偶数)
define kLimitLength 146
@interface SEPrinterManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (copy,nonatomic) SEScanPerpheralSuccess scanPerpheralSuccess; /*< 扫描设备成功的回调 /
@property (copy, nonatomic) SEScanPerpheralFailure scanPerpheralFailure; /*< 扫描设备失败的回调 /
@property (copy, nonatomic) SEConnectCompletion connectCompletion; /*< 连接完成的回调 /
@property (copy, nonatomic) SEFullOptionCompletion optionCompletion; /*< 连接、扫描、搜索 /
@property (copy, nonatomic) SEDisconnect disconnectBlock; /*< 断开连接的回调 /
@property (strong, nonatomic) SEPrintResult printResult; /*< 打印结果的回调 /
@property (strong, nonatomic) CBCentralManager *centralManager; /*< 中心管理器 /
@property (strong, nonatomic) CBPeripheral *connectedPerpheral; /*< 当前连接的外设 /
@property (strong, nonatomic) NSMutableArray *perpherals; /*< 搜索到的蓝牙设备列表 /
@property (strong, nonatomic) NSMutableArray *writeChatacters; /*< 可写入数据的特性 /
@property (assign, nonatomic) NSTimeInterval timeout; /*< 默认超时时间 /
@property (strong, nonatomic) HLPrinter *printer; /*< 打印器 /
@property (assign, nonatomic) BOOL autoConnect; /*< 自动连接上次的外设 /
@property (assign, nonatomic) NSInteger writeCount; /*< 写入次数 /
@property (assign, nonatomic) NSInteger responseCount; /*< 返回次数 /
@end
static SEPrinterManager *instance = nil;
@implementation SEPrinterManager
- (instancetype)sharedInstance
{
return [[self alloc] init];
}
- (NSString *)UUIDStringForLastPeripheral
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *UUIDString = [userDefaults objectForKey:@"peripheral"];
return UUIDString;
}
- (instancetype)init
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super init];
instance.perpherals = [[NSMutableArray alloc] init];
instance.writeChatacters = [[NSMutableArray alloc] init];
instance.timeout = 30;
[instance resetBLEModel];
});
return instance;
}
- (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
pragma mark - bluetooth method
- (void)setTimeout:(NSTimeInterval)timeout
{
_timeout = timeout;
if (_timeout > 0) {
[self performSelector:@selector(timeoutAction) withObject:nil afterDelay:timeout];
}
}
- (void)timeoutAction
{
[_centralManager stopScan];
if (_perpherals.count == 0) {
//分发错误信息
if (_delegate && [_delegate respondsToSelector:@selector(printerManager:scanError:)]) {
[_delegate printerManager:self scanError:SEScanErrorTimeout];
}
if (_scanPerpheralFailure) {
_scanPerpheralFailure(SEScanErrorTimeout);
}
} else {
if (_delegate && [_delegate respondsToSelector:@selector(printerManager:perpherals:isTimeout:)]) {
[_delegate printerManager:self perpherals:_perpherals isTimeout:YES];
}
if (_scanPerpheralSuccess) {
_scanPerpheralSuccess(_perpherals,YES);
}
}
}
- (BOOL)isConnected
{
if (!_connectedPerpheral) {
return NO;
}
if (_connectedPerpheral.state != CBPeripheralStateConnected && _connectedPerpheral.state != CBPeripheralStateConnecting) {
return NO;
}
return YES;
}
- (void)resetBLEModel
{
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
[_perpherals removeAllObjects];
_scanPerpheralSuccess = nil;
_connectedPerpheral = nil;
}
- (void)startScanPerpheralTimeout:(NSTimeInterval)timeout
{
self.timeout = timeout;
if (_centralManager.state == CBCentralManagerStatePoweredOn) {
[_centralManager scanForPeripheralsWithServices:nil options:nil];
return;
}
[self resetBLEModel];
}
- (void)startScanPerpheralTimeout:(NSTimeInterval)timeout Success:(SEScanPerpheralSuccess)success failure:(SEScanPerpheralFailure)failure
{
self.timeout = timeout;
_scanPerpheralSuccess = success;
_scanPerpheralFailure = failure;
NSLog(@"_centralManager.state:%ld",_centralManager.state);
if (_centralManager.state == CBCentralManagerStatePoweredOn) {
[_centralManager scanForPeripheralsWithServices:nil options:nil];
return;
}
[self resetBLEModel];
}
pragma mark - CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (central.state != CBCentralManagerStatePoweredOn) {
if (_delegate && [_delegate respondsToSelector:@selector(printerManager:scanError:)]) {
[_delegate printerManager:self scanError:(SEScanError)central.state];
}
if (_scanPerpheralFailure) {
_scanPerpheralFailure((SEScanError)central.state);
}
} else {
[central scanForPeripheralsWithServices:nil options:nil];
}
}
- (void)centralManager:(CBCentralManager )central didDiscoverPeripheral:(CBPeripheral )peripheral advertisementData:(NSDictionary<NSString , id> )advertisementData RSSI:(NSNumber *)RSSI
{
if (peripheral.name.length <= 0) {
return ;
}
NSLog(@"Discovered name:%@,identifier:%@,advertisementData:%@,RSSI:%@", peripheral.name, peripheral.identifier,advertisementData,RSSI);
if(_perpherals.count==0){
[_perpherals addObject:peripheral];
}else{
BOOL isExist = NO;
for (int i = 0; i < _perpherals.count; i++) {
CBPeripheral *per = [_perpherals objectAtIndex:i];
if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
isExist = YES;
[_perpherals replaceObjectAtIndex:i withObject:peripheral];
}
}
if (!isExist) {
[_perpherals addObject:peripheral];
}
}
if (_delegate && [_delegate respondsToSelector:@selector(printerManager:perpherals:isTimeout:)]) {
[_delegate printerManager:self perpherals:_perpherals isTimeout:NO];
}
if (_scanPerpheralSuccess) {
_scanPerpheralSuccess(_perpherals,NO); //这一步 报错,野指针,,不知道什么问题。求解???
}
if (_autoConnect) {
NSString *UUIDString = [SEPrinterManager UUIDStringForLastPeripheral];
if ([peripheral.identifier.UUIDString isEqualToString:UUIDString]) {
[_centralManager connectPeripheral:peripheral options:nil];
peripheral.delegate = self;
}
}
}
@end
0 个回复