//
//  ENHMDGlucoDevice.m
//  ENBLEProject
//
//  Created by lvwang2002 on 16/4/7.
//  Copyright © 2016年 Facebook. All rights reserved.
//

#import "ENHMDGlucoDevice.h"
static NSString *displayName = @"好轻松血糖仪";
@implementation ENHMDGlucoDevice{
	NSArray *_characteristics;
}
-(id)initWithPeripheral:(CBPeripheral *)peripheral WithCentralManager:(CBCentralManager *)centerManager WithDevice:(BLEDevice *)device{
	self = [super initWithPeripheral:peripheral WithCentralManager:centerManager WithDevice:device];
	if(self){
		
		
	}
	return self;
}

-(NSString *)getDeviceDisplayName{
	return displayName;
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
	if (error){
		NSLog(@"didDiscoverServices : %@", [error localizedDescription]);
		return;
	}
	
	for (CBService * service in peripheral.services) {
		/**
		 *  查找自己需要的UUID的服务
		 */
		
			//        if ([[self.advertisementData[@"kCBAdvDataServiceUUIDs"] firstObject] isEqual:service.UUID]) {
		
		/**
		 *  查找外围设备特性
		 */
		[peripheral discoverCharacteristics:nil forService:service];
		
	}
}

- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
															 error:(NSError *)error{
	if (error){
		NSLog(@"didDiscoverCharacteristicsForService error : %@", [error localizedDescription]);
		return;
	}
	
	_characteristics = service.characteristics;
	
	for (CBCharacteristic * cbCharacteristic in service.characteristics) {
		
//		NSLog(@"获取的UUID为：%@", cbCharacteristic.UUID.UUIDString);
		
		if ([cbCharacteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A18"]]) {
			[peripheral setNotifyValue:YES forCharacteristic:cbCharacteristic];
		}
		
		if ([cbCharacteristic.UUID.UUIDString isEqual:@"2A25"]) {
			[peripheral readValueForCharacteristic:cbCharacteristic];
		}
	}
}

//- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
//	[self caculateWithData:[characteristic value]];
//}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForReceiveData:(NSData *)data UUID:(CBUUID *)uuid error:(NSError *)error{
	[self caculateWithData:data];
}


#pragma mark - 计算
- (void)caculateWithData:(NSData *)data{
	Byte * byte = (Byte *)[data bytes];
	NSString *hexStr=@"";
	NSMutableArray * array = [NSMutableArray array];
	for(int i=0;i<[data length];i++){
		NSString *newHexStr = [NSString stringWithFormat:@"%x",byte[i]&0xff]; ///16进制数
		if([newHexStr length]==1){
			hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
			[array addObject:[NSString stringWithFormat:@"0%@",newHexStr]];
		}else{
			hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
			[array addObject:newHexStr];
		}
	}
//	NSLog(@"bytes 的16进制数为:%@",hexStr);

	
	if (array.count == 15) {
		NSString * str1 = array[array.count - 2];
		NSString * str2 = array[array.count - 3];
		
		NSString *strHex = [NSString stringWithFormat:@"%@%@",str2, str1];
		NSString *strResult = [self getBinaryByhex:strHex];
		
		NSString *strM = [strHex substringWithRange:NSMakeRange(1, 3)];
		NSString *strN = [strResult substringWithRange:NSMakeRange(0, 4)];
		NSLog(@"---%@", strResult);
		
		unsigned long resultM = [self getLongIntWithString:strM];
		unsigned long resultN = [self getIntWithString:strN];
		
		float myResultValue = resultM;
		float resultP = powl(10, (16 - resultN));
		
		float resultBlood = myResultValue / resultP;
		NSLog(@"blood %@",@(resultBlood));
//		info[@"Glucose"] = @((b[9]&0xff) + 256*(b[10]&0xff));
		
		dispatch_async(dispatch_get_main_queue(), ^{
			NSString *glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)resultBlood,((int)(resultBlood*10)%10)];
			NSDictionary *info = @{
														 @"Glucose":@(resultBlood),
														 @"displayValue":glucoseValue} ;

			if([self.deviceDelegate respondsToSelector:@selector(getResult:WithDevice:)]){
				[(id)self.deviceDelegate getResult:info WithDevice:_device];
			}
		});

		
	} else {
		NSLog(@"code is %@",hexStr);
	}
}

	//将16进制转化为二进制
-(NSString *)getBinaryByhex:(NSString *)hex
{
	NSMutableDictionary  *hexDic = [[NSMutableDictionary alloc] init];
	
	hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
	
	[hexDic setObject:@"0000" forKey:@"0"];
	
	[hexDic setObject:@"0001" forKey:@"1"];
	
	[hexDic setObject:@"0010" forKey:@"2"];
	
	[hexDic setObject:@"0011" forKey:@"3"];
	
	[hexDic setObject:@"0100" forKey:@"4"];
	
	[hexDic setObject:@"0101" forKey:@"5"];
	
	[hexDic setObject:@"0110" forKey:@"6"];
	
	[hexDic setObject:@"0111" forKey:@"7"];
	
	[hexDic setObject:@"1000" forKey:@"8"];
	
	[hexDic setObject:@"1001" forKey:@"9"];
	
	[hexDic setObject:@"1010" forKey:@"A"];
	
	[hexDic setObject:@"1011" forKey:@"B"];
	
	[hexDic setObject:@"1100" forKey:@"C"];
	
	[hexDic setObject:@"1101" forKey:@"D"];
	
	[hexDic setObject:@"1110" forKey:@"E"];
	
	[hexDic setObject:@"1111" forKey:@"F"];
	
	[hexDic setObject:@"1010" forKey:@"a"];
	
	[hexDic setObject:@"1011" forKey:@"b"];
	
	[hexDic setObject:@"1100" forKey:@"c"];
	
	[hexDic setObject:@"1101" forKey:@"d"];
	
	[hexDic setObject:@"1110" forKey:@"e"];
	
	[hexDic setObject:@"1111" forKey:@"f"];
	
	NSMutableString *binaryString=[[NSMutableString alloc] init];
	
	for (int i=0; i<[hex length]; i++) {
		
		NSRange rage;
		
		rage.length = 1;
		
		rage.location = i;
		
		NSString *key = [hex substringWithRange:rage];
		
			//NSLog(@"%@",[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]);
		
		binaryString = [[NSString stringWithFormat:@"%@%@",binaryString,[NSString stringWithFormat:@"%@",[hexDic objectForKey:key]]] mutableCopy];
		
	}
	
		//NSLog(@"转化后的二进制为:%@",binaryString);
	
	return binaryString;
}

#pragma mark - 二进制转变成十进制
- (unsigned long)getIntWithString:(NSString *)hex
{
	unsigned long resultValue = 0;
	
	for (NSInteger j = 0; j < hex.length; j++) {
		char value = [hex characterAtIndex:j];
		NSInteger i = hex.length - 1 - j;
		if (value == '0') {
			resultValue += 0 * powl(2, i);
		} else if (value == '1') {
			resultValue += 1 * powl(2, i);
		}
	}
	
	return resultValue;
}

#pragma mark - 十六进制转变成十进制
- (unsigned long)getLongIntWithString:(NSString *)hex
{
	unsigned long resultValue = 0;
	
	for (NSInteger j = 0; j < hex.length; j++) {
		char value = [hex characterAtIndex:j];
		NSInteger i = hex.length - 1 - j;
		
		NSInteger valueR = [self charToInt:value];
		resultValue += valueR * powl(16, i);
	}
	return resultValue;
}

- (NSInteger)charToInt:(char)value
{
	if (value == '0') {
		return 0;
	} else if (value == '1') {
		return 1;
	} else if (value == '2') {
		return 2;
	} else if (value == '3') {
		return 3;
	} else if (value == '4') {
		return 4;
	} else if (value == '5') {
		return 5;
	} else if (value == '6') {
		return 6;
	} else if (value == '7') {
		return 7;
	} else if (value == '8') {
		return 8;
	} else if (value == '9') {
		return 9;
	} else if (value == 'a') {
		return 10;
	} else if (value == 'A') {
		return 10;
	} else if (value == 'b') {
		return 11;
	} else if (value == 'B') {
		return 11;
	} else if (value == 'c') {
		return 12;
	} else if (value == 'C') {
		return 12;
	} else if (value == 'd') {
		return 13;
	} else if (value == 'D') {
		return 13;
	} else if (value == 'e') {
		return 14;
	} else if (value == 'E') {
		return 14;
	} else if (value == 'f') {
		return 15;
	} else if (value == 'F') {
		return 15;
	}
	
	return 0;
}
@end
