//
// MKBluetoothPrinter.m
// CordovaDemo
//
// Created by xmk on 2017/6/20.
//
//

#import "MKBluetoothPrinter.h"
#import "HLBLEManager.h"
#import "HLPrinter.h"
#import "MKConst.h"
#import "MKPrinterInfoModel.h"

@interface MKBluetoothPrinter ()
@property (nonatomic, strong) HLBLEManager *manager;
@property (nonatomic, strong) NSMutableArray *peripheralsArray; /*!< å¤–è®¾åˆ—è¡¨ */
@property (nonatomic, copy ) NSString *scanPeripheralsCallBackId; /*!< æ‰«æ æŽ¥å£ callBackId, ç”¨äºŽæŒç»å›žè°ƒJS*/
@property (nonatomic, strong) CBPeripheral *connectPeripheral; /*!< è¿žæŽ¥çš„å¤–è®¾ */
@property (nonatomic, strong) CBCharacteristic *chatacter; /*!< å¯å†™å…¥æ•°æ®çš„ç‰¹æ€§ */
@property (nonatomic, strong) NSMutableArray *servicesArray; /*!< å¤–è®¾ æœåŠ¡åˆ—è¡¨ */
//@property (nonatomic, strong) HLPrinter *printerInfo; /*!< æ‰“å°æ•°æ® */
@property (nonatomic, strong) NSMutableArray *printerModelArray; /*!< æ‰“å°ä¿¡æ¯æ•°ç»„ ä¸»è¦ç”¨äºŽæŽ’åº*/
@end

@implementation MKBluetoothPrinter

/*
* è®¾ç½®æ‰“å°æœºçº¸å¼ å®½åº¦
*/
- (void)setPrinterPageWidth:(CDVInvokedUrlCommand *)command{
if (command.arguments.count > 0 && command.arguments[0] != [NSNull null]) {
NSString *param = command.arguments[0];
NSInteger width = param.integerValue;
if (width > 0) {
[HLPrinter sharedInstance].pageWidth = width;
[self callBackSuccess:YES callBackId:command.callbackId message:[NSString stringWithFormat:@"è®¾ç½®çº¸å¼ å®½åº¦æˆåŠŸ:%ld",width]];
return;
}
}
[self callBackSuccess:NO callBackId:command.callbackId message:@"error: not find param with page width || page width <= 0"];
}

/*
* èŽ·å–å½“å‰è®¾ç½®çš„æ‰“å°æœºçº¸å¼ å®½åº¦
*/
- (void)getCurrentSetPageWidth:(CDVInvokedUrlCommand *)command{
NSInteger cacheWidth = [HLPrinter sharedInstance].pageWidth;
[self callBackSuccess:YES callBackId:command.callbackId message:[NSString stringWithFormat:@"%ld",cacheWidth]];
}

/** è®¾ç½® é¦–åˆ— æœ€å¤§å—ç¬¦ä¸²é•¿åº¦ */
- (void)setFirstRankMaxLength:(CDVInvokedUrlCommand *)command{
if (command.arguments.count > 1) {
if (command.arguments[0] != [NSNull null]){
NSInteger length = [command.arguments[0] integerValue];
if (length > 0) {
[HLPrinter sharedInstance].maxLength3Text = length;
}
}
if (command.arguments[1] != [NSNull null]){
NSInteger length = [command.arguments[1] integerValue];
if (length > 0) {
[HLPrinter sharedInstance].maxLength4Text = length;
}
}
[[NSUserDefaults standardUserDefaults] synchronize];
[self callBackSuccess:YES callBackId:command.callbackId message:[NSString stringWithFormat:@"è®¾ç½®æˆåŠŸ"]];
return;
}
[self callBackSuccess:NO callBackId:command.callbackId message:@"å‚æ•°ä¸ºæ•°å—æ•°ç»„ï¼Œä¾‹ [16,20]"];

}

/** è‡ªåŠ¨è¿žæŽ¥ */
- (void)autoConnectPeripheral:(CDVInvokedUrlCommand *)command{
[self autoConnectPeripheral];
}

/** æ˜¯å¦å·²è¿žæŽ¥ */
- (void)isConnectPeripheral:(CDVInvokedUrlCommand *)command{
NSString *b = [self isConnectPeripheral] ? @"1" : @"0";
[self callBackSuccess:YES callBackId:command.callbackId message:b];
}

#pragma mark - ***** scan peripherals *****
- (void)scanForPeripherals:(CDVInvokedUrlCommand *)command{
[self.commandDelegate runInBackground:^{
BOOL bKeepCallBack = NO;
if (command.arguments.count > 0 && command.arguments[0] && command.arguments[0] != [NSNull null]) {
if ([command.arguments[0] isKindOfClass:[NSNumber class]] || [command.arguments[0] isKindOfClass:[NSString class]]) {
bKeepCallBack = [command.arguments[0] integerValue] == 1;
}else{
ELog(@"warn: param tyep error, if you need keep callback, place input '1'");
}
}

self.scanPeripheralsCallBackId = nil;
self.scanPeripheralsCallBackId = command.callbackId.copy;

__weak MKBluetoothPrinter *weakSelf = self;
[self scanForPeripheralsWithBlock:^(BOOL success, NSString *message) {
if (success) {
[weakSelf callBackPeripheralsWithKeep:bKeepCallBack];
}else{
[weakSelf callBackSuccess:success callBackId:command.callbackId message:message keep:YES];
}
}];
}];
}

- (void)callBackPeripheralsWithKeep:(BOOL)keep{
NSMutableArray *peripherals = [self getPeripheralList];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray: peripherals];
[pluginResult setKeepCallbackAsBool:keep];
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.scanPeripheralsCallBackId];
}

- (void)stopScan:(CDVInvokedUrlCommand *)command{
[self.manager stopScan];
[self callBackSuccess:YES callBackId:command.callbackId message:@"stop scan success"];
}

/** get peripherals */
- (void)getPeripherals:(CDVInvokedUrlCommand *)command{
NSMutableArray *peripherals = [self getPeripheralList];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray: peripherals];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

/** connect Peripheral */
- (void)connectPeripheral:(CDVInvokedUrlCommand *)command{
if (command.arguments.count <= 0) {
[self callBackSuccess:NO callBackId:command.callbackId message:@"error: please input the peripheral's uuid or name"];
return;
}

NSString *peripheralId = nil;
if ([command.arguments[0] isKindOfClass:[NSString class]] && [command.arguments[0] length] > 0){
peripheralId = command.arguments[0];
}else{
[self callBackSuccess:NO callBackId:command.callbackId message:@"error: param error"];
return;
}

__weak MKBluetoothPrinter *weakSelf = self;
[self connectPeripheralWith:peripheralId block:^(BOOL success, NSString *message) {
[weakSelf callBackSuccess:success callBackId:command.callbackId message:message];
}];
}

/** set printer info and printer */
- (void)setPrinterInfoAndPrinter:(CDVInvokedUrlCommand *)command{
[self.commandDelegate runInBackground:^{
if (command.arguments.count > 0 && command.arguments[0] != [NSNull null]) {
NSString *jsonStr = command.arguments[0];
__weak MKBluetoothPrinter *weakSelf = self;
[self setPrinterInfoWithJsonString:jsonStr block:^(BOOL success, NSString *message) {
if (success) {
[weakSelf finalPrinterWithBlock:^(BOOL success, NSString *message) {
[weakSelf callBackSuccess:success callBackId:command.callbackId message:message];
}];
}else{
[weakSelf callBackSuccess:success callBackId:command.callbackId message:message];
}
}];
}else{
[self callBackSuccess:NO callBackId:command.callbackId message:@"error: not find param with printer info"];
}
}];
}

/** æ–å¼€è¿žæŽ¥ */
- (void)stopPeripheralConnection:(CDVInvokedUrlCommand *)command{
[self stopPeripheralConnection];
[self callBackSuccess:YES callBackId:command.callbackId message:@"stop peripheral connection"];
}

/** æŽ§åˆ¶å°æ‰“å° log */
- (void)printLog:(CDVInvokedUrlCommand *)command{
NSString *log = @"";
if (command.arguments.count > 0) {
for (int i = 0; i < command.arguments.count; i++) {
if ([command.arguments[i] isKindOfClass:[NSString class]]) {
log = [log stringByAppendingString:command.arguments[i]];
}
}
}
[self consoleLog:log];
}

#pragma mark - ***** call back *****
- (void)callBackSuccess:(BOOL)success callBackId:(NSString *)callBackId message:(NSString *)message{
[self callBackSuccess:success callBackId:callBackId message:message keep:NO];
}

- (void)callBackSuccess:(BOOL)success callBackId:(NSString *)callBackId message:(NSString *)message keep:(BOOL)keep{
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:success?CDVCommandStatus_OK:CDVCommandStatus_ERROR messageAsString:message];
[pluginResult setKeepCallbackAsBool:keep];
[self.commandDelegate sendPluginResult:pluginResult callbackId:callBackId];
}

#pragma mark - **************************************************
#pragma mark - ***** OC method *****
- (BOOL)isConnectPeripheral{
BOOL b = self.connectPeripheral && self.manager.connectedPerpheral;
return b;
}

/** æ‰«æ å¹¶è¿žæŽ¥ è®¾å¤‡ åŽ†å²è®¾å¤‡ */
- (void)autoConnectPeripheral{
if ([self isConnectPeripheral]) {
ELog(@"å·²è¿žæŽ¥");
return;
}
NSString *peripheralName = [self getHistoryPeripheralName];
if (peripheralName) {
if (self.peripheralsArray.count > 0){
__weak MKBluetoothPrinter *weakSelf = self;
[self connectPeripheralWith:peripheralName block:^(BOOL success, NSString *message) {
if (success) {
ELog(@"autoConnectPeripheral : %@", message);
}else{
[weakSelf scanPeripheralsAndConnectWithPeripheralName:peripheralName];
}
}];
return;
}
[self scanPeripheralsAndConnectWithPeripheralName:peripheralName];
}else{
ELog(@"æ— åŽ†å²è¿žæŽ¥è®¾å¤‡");
}
}

- (void)scanPeripheralsAndConnectWithPeripheralName:(NSString *)name{
__weak MKBluetoothPrinter *weakSelf = self;
[self scanForPeripheralsWithBlock:^(BOOL success, NSString *message) {
if (success && weakSelf.peripheralsArray.count > 0) {
[self connectPeripheralWith:name block:nil];
}
}];
}

/** æ‰«æè®¾å¤‡ */
- (void)scanForPeripheralsWithBlock:(CommandBlcok)block{
__weak MKBluetoothPrinter *weakSelf = self;
if (self.manager.stateUpdateBlock) {
//å·²ç»è®¾ç½®è¿‡çŠ¶æ€å›žè°ƒï¼Œç›´æŽ¥å¼€å§‹æ‰«æ
[self starScanWithBlock:block];
}else{
//æ£€æŸ¥è“ç‰™ çŠ¶æ€ï¼Œå¼€å§‹æ‰«æ
self.manager.stateUpdateBlock = ^(CBCentralManager *central) {
NSString *info = nil;
switch (central.state) {
case CBCentralManagerStatePoweredOn:{
[weakSelf starScanWithBlock:block];
}
return;
case CBCentralManagerStatePoweredOff:
info = @"è“ç‰™å¯ç”¨ï¼Œæœªæ‰“å¼€";
break;
case CBCentralManagerStateUnsupported:
info = @"SDKä¸æ”¯æŒ";
break;
case CBCentralManagerStateUnauthorized:
info = @"ç¨‹åºæœªæŽˆæƒ";
break;
case CBCentralManagerStateResetting:
info = @"CBCentralManagerStateResetting";
break;
case CBCentralManagerStateUnknown:
info = @"CBCentralManagerStateUnknown";
break;
default:
break;
}
ELog(@"%@", info);
MKBlockExec(block, NO, info);
};
}
}
/** å¼€å§‹æ‰«æ */
- (void)starScanWithBlock:(CommandBlcok)block{
__weak MKBluetoothPrinter *weakSelf = self;
[self.manager scanForPeripheralsWithServiceUUIDs:nil options:nil didDiscoverPeripheral:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
ELog(@"peripheral.name : %@", peripheral.name);
if (peripheral.name.length <= 0) {
return ;
}
BOOL isExist = NO;
for (int i = 0; i < weakSelf.peripheralsArray.count; i++) {
CBPeripheral *per = weakSelf.peripheralsArray[i];
// ELog(@"UUIDString %zd :%@",i, per.identifier.UUIDString);
if ([per.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
isExist = YES;
[weakSelf.peripheralsArray replaceObjectAtIndex:i withObject:peripheral];
break;
}
}
if (!isExist) {
[weakSelf.peripheralsArray addObject:peripheral];
}
MKBlockExec(block, YES, nil);
return;
}];
}

- (NSMutableArray *)getPeripheralList {
NSMutableArray *peripherals = @[].mutableCopy;
for (int i = 0; i < self.peripheralsArray.count; i++) {
NSMutableDictionary *peripheralDic = @{}.mutableCopy;
CBPeripheral *p = [self.peripheralsArray objectAtIndex:i];

NSString *uuid = p.identifier.UUIDString;
[peripheralDic setObject:uuid forKey:@"uuid"];
NSString *name = [p name];
if (!name) {
name = [peripheralDic objectForKey:@"uuid"];
}
[peripheralDic setObject:name forKey:@"name"];
[peripherals addObject:peripheralDic];
}
return peripherals;
}

/** è¿žæŽ¥è®¾å¤‡ */
- (void)connectPeripheralWith:(NSString *)string block:(CommandBlcok)block{
if (string) {
ELog(@"peripheral:%@",string);
for (CBPeripheral *per in self.peripheralsArray) {
if ([per.identifier.UUIDString isEqualToString:string]) {
self.connectPeripheral = per;
}else if ([per.name isEqualToString:string]){
self.connectPeripheral = per;
}
}
}
if (self.connectPeripheral == nil) {
MKBlockExec(block, NO, [NSString stringWithFormat:@"error: no find the peripheral : %@", string]);
return;
}
__weak MKBluetoothPrinter *weakSelf = self;
[self.manager connectPeripheral:self.connectPeripheral
connectOptions:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}
stopScanAfterConnected:YES
servicesOptions:nil
characteristicsOptions:nil
completeBlock:^(HLOptionStage stage, CBPeripheral *peripheral, CBService *service, CBCharacteristic *character, NSError *error) {
NSString *statusStr = @"";
switch (stage) {
case HLOptionStageConnection:{
if (error) {
statusStr = @"error: connect fail";
weakSelf.connectPeripheral = nil;
MKBlockExec(block, NO, statusStr);
} else {
statusStr = @"connect success";
[weakSelf savePeripheralName:weakSelf.connectPeripheral.name];
NSString *str = [NSString stringWithFormat:@"{\"uuid\":%@,\"name\":%@}", weakSelf.connectPeripheral.name, weakSelf.connectPeripheral.identifier.UUIDString];
MKBlockExec(block, YES, str);
return ;
}
break;
}
case HLOptionStageSeekServices:{
if (error) {
statusStr = @"æŸ¥æ‰¾æœåŠ¡å¤±è´¥";
} else {
statusStr = @"æŸ¥æ‰¾æœåŠ¡æˆåŠŸ";
[self.servicesArray addObjectsFromArray:peripheral.services];
}
break;
}
case HLOptionStageSeekCharacteristics:{
// è¯¥blockä¼šè¿”å›žå¤šæ¬¡ï¼Œæ¯ä¸€ä¸ªæœåŠ¡è¿”å›žä¸€æ¬¡
if (error) {
statusStr = @"æŸ¥æ‰¾ç‰¹æ€§å¤±è´¥";
} else {
statusStr = @"æŸ¥æ‰¾ç‰¹æ€§æˆåŠŸ";
}
break;
}
case HLOptionStageSeekdescriptors:{
// è¯¥blockä¼šè¿”å›žå¤šæ¬¡ï¼Œæ¯ä¸€ä¸ªç‰¹æ€§è¿”å›žä¸€æ¬¡
if (error) {
statusStr = @"æŸ¥æ‰¾ç‰¹æ€§çš„æè¿°å¤±è´¥";
} else {
statusStr = @"æŸ¥æ‰¾ç‰¹æ€§çš„æè¿°æˆåŠŸ";
}
break;
}
default:
break;
}
ELog(@"connectPeripheral status : %@", statusStr);
}];

}

/** è®¾ç½®æ‰“å°ä¿¡æ¯ */
- (void)setPrinterInfoWithJsonString:(NSString *)jsonStr block:(CommandBlcok)block{
ELog(@"jsonStr : %@", jsonStr);
if (jsonStr == nil || jsonStr.length == 0) {
MKBlockExec(block, NO, @"error: param invalid");
return;
}
NSArray *array = [jsonStr mk_jsonString2Dictionary];
if (array == nil || ![array isKindOfClass:[NSArray class]] || array.count == 0) {
MKBlockExec(block, NO, @"error: json format error");
return;
}
[self setPrinterInfoWithArray:array block:block];
MKBlockExec(block, YES, @"set printer info success");
}

- (void)setPrinterInfoWithArray:(NSArray *)array block:(CommandBlcok)block{
[self.printerModelArray removeAllObjects];
[self.printerModelArray addObjectsFromArray:array];
[self clearPrinterInfo];

for (NSDictionary *dic in self.printerModelArray) {
MKPrinterInfoModel *model = [[MKPrinterInfoModel alloc] init];
if ([dic valueForKey:@"infoType"]) {
model.infoType = [[dic valueForKey:@"infoType"] integerValue];
}
if ([dic valueForKey:@"text"]){
if ([[dic valueForKey:@"text"] isKindOfClass:[NSString class]]) {
model.text = [dic valueForKey:@"text"];
}else{
model.text = [[dic valueForKey:@"text"] stringValue];
}
}
if ([dic valueForKey:@"textArray"]){
model.textArray = [dic valueForKey:@"textArray"];
}
if ([dic valueForKey:@"fontType"]){
model.fontType = [[dic valueForKey:@"fontType"] integerValue];
}
if ([dic valueForKey:@"aligmentType"]){
model.aligmentType = [[dic valueForKey:@"aligmentType"] integerValue];
}
if ([dic valueForKey:@"maxWidth"]){
model.maxWidth = [[dic valueForKey:@"maxWidth"] floatValue];
}
if ([dic valueForKey:@"qrCodeSize"]){
model.qrCodeSize = [[dic valueForKey:@"qrCodeSize"] floatValue];
}
if ([dic valueForKey:@"offset"]){
model.offset = [[dic valueForKey:@"offset"] floatValue];
}
if ([dic valueForKey:@"isTitle"]){
model.isTitle = [[dic valueForKey:@"isTitle"] integerValue];
}

switch (model.infoType) {
case MKBTPrinterInfoType_text:
[[HLPrinter sharedInstance] appendText:model.text alignment:[model getAlignment] fontSize:[model getFontSize]];
break;
case MKBTPrinterInfoType_textList:{
[self appentTextListWith:model];
}
break;
case MKBTPrinterInfoType_barCode:
[[HLPrinter sharedInstance] appendBarCodeWithInfo:model.text alignment:[model getAlignment] maxWidth:model.maxWidth];
break;
case MKBTPrinterInfoType_qrCode:
// [self.printerInfo appendQRCodeWithInfo:model.text size:model.qrCodeSize alignment:[model getAlignment]];
[[HLPrinter sharedInstance] appendQRCodeWithInfo:model.text];
break;
case MKBTPrinterInfoType_image:{
UIImage *image = [UIImage mk_imageWithBase64:model.text];
if (image) {
[[HLPrinter sharedInstance] appendImage:image alignment:[model getAlignment] maxWidth:model.maxWidth];
}
}
break;
case MKBTPrinterInfoType_seperatorLine:
[[HLPrinter sharedInstance] appendSeperatorLine];
break;
case MKBTPrinterInfoType_spaceLine:
[[HLPrinter sharedInstance] appendSpaceLine];
break;
case MKBTPrinterInfoType_footer:
[[HLPrinter sharedInstance] appendFooter:model.text];
break;
case MKBTPrinterInfoType_cutpage:
[[HLPrinter sharedInstance] appendCutPaper];
break;
default:
break;
}
}
if ([HLPrinter sharedInstance].pageWidth == 58) {
[[HLPrinter sharedInstance] appendNewLine];
[[HLPrinter sharedInstance] appendNewLine];
}
// [self.printerInfo appendCutPaper];
}

- (void)appentTextListWith:(MKPrinterInfoModel *)model{
NSMutableArray *tempAry = @[].mutableCopy;
for (id obj in model.textArray) {
if ([obj isKindOfClass:[NSString class]]) {
[tempAry addObject:obj];
}else{
[tempAry addObject:[obj stringValue]];
}
}

if (model.textArray.count == 2) {
[[HLPrinter sharedInstance] appendTitle:tempAry[0] value:tempAry[1]];
}else if (model.textArray.count == 3 || model.textArray.count == 4){
[self printerRowTextInfoWith:model.textArray isTitle:model.isTitle == 1];
}
}

- (void)printerRowTextInfoWith:(NSArray *)textAry isTitle:(BOOL)isTitle{
if (textAry.count == 3) {
NSString *str = [textAry objectAtIndex:0];
NSString *frontStr = [self getSubString:str max:[HLPrinter sharedInstance].maxLength3Text];
[[HLPrinter sharedInstance] appendLeftText:frontStr middleText:textAry[1] rightText:textAry[2] isTitle:isTitle];
if (str.length > frontStr.length) {
NSString *subStr = [str substringFromIndex:frontStr.length];
NSMutableArray *nextAry = [NSMutableArray arrayWithObjects:subStr, @" ", @" ", nil];
[self printerRowTextInfoWith:nextAry isTitle:isTitle];
}
}else if (textAry.count == 4){
NSString *str = [textAry objectAtIndex:0];
NSString *frontStr = [self getSubString:str max:[HLPrinter sharedInstance].maxLength4Text];
NSMutableArray *ary = [NSMutableArray arrayWithObjects:frontStr, textAry[1], textAry[2], textAry[3], nil];
[[HLPrinter sharedInstance] appendTextArray:ary isTitle:isTitle];
if (str.length > frontStr.length) {
NSString *subStr = [str substringFromIndex:frontStr.length];
NSMutableArray *nextAry = [NSMutableArray arrayWithObjects:subStr, @" ", @" ", @" ", nil];
[self printerRowTextInfoWith:nextAry isTitle:isTitle];
}
}
}

- (NSString *)getSubString:(NSString *)str max:(NSInteger)maxChar{
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData *data = [str dataUsingEncoding:enc];
if (data.length > maxChar) {
data = [data subdataWithRange:NSMakeRange(0, maxChar)];
str = [[NSString alloc] initWithData:data encoding:enc];
if (!str) {
data = [data subdataWithRange:NSMakeRange(0, maxChar - 1)];
str = [[NSString alloc] initWithData:data encoding:enc];
}
}
return str;
// int length = 0;
// NSInteger index = 0;
// for (NSInteger i = 0; i < str.length; i++) {
// unichar a = [str characterAtIndex:i];
// if ([self isChinese:a]) {
// length = length + 2;
// }else{
// length = length + 1;
// }
// if (length <= maxChar) {
// index = index + 1;
// }else{
// break;
// }
// }
// return [str substringToIndex:index];
}

/** æ˜¯å¦æ˜¯æ±‰å— */
- (BOOL)isChinese:(unichar)word{
if( word >= 0x4e00 && word <= 0x9fff){
return YES;
}
return NO;
}

- (void)finalPrinterWithBlock:(CommandBlcok)block{
if (self.servicesArray.count > 0) {
for (CBService *service in self.servicesArray) {
for (CBCharacteristic *character in service.characteristics) {
CBCharacteristicProperties properties = character.properties;
if (properties & CBCharacteristicPropertyWrite) {
self.chatacter = character;
}
}
}
}

if (self.chatacter == nil) {
MKBlockExec(block, NO, @"error: no find the service with can write");
return;
}

NSData *mainData = [[HLPrinter sharedInstance] getFinalData];
if (self.chatacter.properties & CBCharacteristicPropertyWrite) {
[self.manager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithResponse completionBlock:^(CBCharacteristic *characteristic, NSError *error) {
if (!error) {
MKBlockExec(block, YES, @"printer sucess");
}else{
MKBlockExec(block, NO, @"printer fail");
}
}];
} else if (self.chatacter.properties & CBCharacteristicPropertyWriteWithoutResponse) {
[self.manager writeValue:mainData forCharacteristic:self.chatacter type:CBCharacteristicWriteWithoutResponse];
}

}

- (void)stopPeripheralConnection{
self.connectPeripheral = nil;
[self.manager cancelPeripheralConnection];
}

- (void)clearPrinterInfo{
[[HLPrinter sharedInstance] defaultSetting];
}

- (void)consoleLog:(NSString *)log{
ELog(@"%@",log);
}

#pragma mark - ***** save periphera name *****
- (void)savePeripheralName:(NSString *)name{
[[NSUserDefaults standardUserDefaults] setValue:name forKey:@"PeripheralName"];
[[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)getHistoryPeripheralName{
return [[NSUserDefaults standardUserDefaults] valueForKey:@"PeripheralName"];
}

#pragma mark - ***** lazy *****
- (HLBLEManager *)manager{
if (!_manager) {
_manager = [HLBLEManager sharedInstance];
}
return _manager;
}

//- (HLPrinter *)printerInfo{
// if (!_printerInfo) {
// _printerInfo = [[HLPrinter alloc] init];
// }
// return _printerInfo;
//}

- (NSMutableArray *)peripheralsArray{
if (!_peripheralsArray) {
_peripheralsArray = @[].mutableCopy;
}
return _peripheralsArray;
}

- (NSMutableArray *)servicesArray{
if (!_servicesArray) {
_servicesArray = @[].mutableCopy;
}
return _servicesArray;
}

- (NSMutableArray *)printerModelArray{
if (!_printerModelArray) {
_printerModelArray = @[].mutableCopy;
}
return _printerModelArray;
}

@end