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

#import "ENGlucoDevice.h"
#import "ENDLog.h"
static  NSString* UUID_BTLE_SERVICE = @"49535343-fe7d-4ae5-8fa9-9fafd205e455";
static  NSString* UUID_BTLE_SEND = @"49535343-8841-43f4-a8d4-ecbe34729bb3";
static	NSString* UUID_BTLE_RECEIVE = @"49535343-1e4d-4bd9-ba61-23c647249616";

static NSString *displayName = @"益优血糖血酮测试仪";

@implementation ENGlucoDevice{
	CBCharacteristic *_sendCharacteristic;
}

-(instancetype)initWithPeripheral:(CBPeripheral *)peripheral WithCentralManager:(CBCentralManager *)centerManager WithDevice:(BLEDevice *)device{
	self = [super initWithPeripheral:peripheral WithCentralManager:centerManager WithDevice:device];
	if(self){

		
	}
	return self;
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
		//找到服务,开始扫描指定的服务
	NSArray *array = [peripheral services];
	
	for( CBService *service in array ){
//		NSString *uuid = [NSString stringWithFormat:@"%@",service.UUID];
		CBUUID *serviceUUID = [CBUUID UUIDWithString:UUID_BTLE_SERVICE];
//		ENDLog([NSString stringWithFormat:@"service uuid%@",serviceUUID]);
		if([serviceUUID isEqual:service.UUID]){
			NSArray *uuids = @[[CBUUID UUIDWithString:UUID_BTLE_SEND],
												 [CBUUID UUIDWithString:UUID_BTLE_RECEIVE]];
			
			[peripheral discoverCharacteristics:uuids forService:service];
			break;
		}
	}
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error;{
	CBUUID *sendUUID = [CBUUID UUIDWithString:UUID_BTLE_SEND];
	CBUUID *receiveUUID = [CBUUID UUIDWithString:UUID_BTLE_RECEIVE];
	
	for( CBCharacteristic *characteristic in service.characteristics){
		NSString *log =[NSString stringWithFormat:@"characteristic is %@",characteristic];
		ENLog(log);
		
		if([characteristic.UUID isEqual:sendUUID]){
			_sendCharacteristic = characteristic;
			unsigned char data[2] = {0xff,0xaa};
//			[peripheral writeValue:[NSData dataWithBytes:&data length:2] forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
			[self sendData:[NSData dataWithBytes:data length:2]];
			continue;
		}
		
		if([characteristic.UUID isEqual:receiveUUID]){
			[peripheral setNotifyValue:YES forCharacteristic:characteristic];
		}
	}
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
	CBUUID *receiveUUID = [CBUUID UUIDWithString:UUID_BTLE_RECEIVE];

	if( [receiveUUID isEqual:characteristic.UUID]){
		[[ENDLog share] log:[NSString stringWithFormat:@"receive gluco data:%@",characteristic.value]];
		if([self checkedCommandIntegrityWithData:characteristic.value]){
			Byte *dat = (Byte *)[[characteristic value] bytes];
			Byte callbackByte[2] = {0xff,dat[2]};
			[self sendData:[NSData dataWithBytes:callbackByte length:2]];
			
			dispatch_async(dispatch_get_main_queue(), ^{
				NSDictionary *info = [self data2GlucoseWithData:[characteristic value]];
				int flag = [info[@"flag"] intValue];
				if(flag>=4096){
					//血酮
					if([self.deviceDelegate respondsToSelector:@selector(getBloodKetoneResult:WithDevice:)]){
						[(id)self.deviceDelegate getBloodKetoneResult:info WithDevice:_device];
					}
				}else{
					//血糖
					if([self.deviceDelegate respondsToSelector:@selector(getResult:WithDevice:)]){
						[(id)self.deviceDelegate getResult:info WithDevice:_device];
					}
				}
			});
		}
	}
}

/** 处理函数 */
-(BOOL)checkedCommandIntegrityWithData:(NSData *)data{
		//长度检测
	if(data.length<7){
		return false;
	}
	
	Byte *b = (Byte *)[data bytes];
	
		//报文头检测
	if(b[0] != 0x40){
		return  false;
	}
	
		//有效命令长度检测
	if(b[3] != (data.length - 6)){
		return false;
	}
	
	
	if([self checkedRepeatCommandWithData:data]){
		return false;
	}
	
	return true;
}



//private static int queId = -1;
/** 校验是否是重复指令 */
-(BOOL)checkedRepeatCommandWithData:(NSData *)data{
	static int queId = -1;
	Byte *b = (Byte *)[data bytes];

	int m = (b[2]&0xff);
	if(m == queId){
		return true;
	}
	//2.将该条命令的顺序id写入缓存
	queId = m;
	
	//4.返回false.
	return false;
}

-(NSDictionary *)data2GlucoseWithData:(NSData *)data{
	Byte *b = (Byte *)[data bytes];
	NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithCapacity:10];
	info[@"year"] = @(2000+(b[6] & 0xff));
	info[@"month"] = @(b[4] & 0xff);
	info[@"date"] = @(b[5] & 0xff);
	info[@"hour"] = @(b[7] & 0xff);
	info[@"minute"] = @(b[8] & 0xff);
	info[@"Glucose"] = @((b[9]&0xff) + 256*(b[10]&0xff));
	info[@"mask"] = @(b[11]&0xff);
	info[@"flag"]= @((b[12]&0xff) + 256*(b[13]&0xff));
	
	
	
	if([info[@"flag"] integerValue]>=4096){
		float value = [info[@"Glucose"] floatValue]/10;
		NSString *displayValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
		info[@"displayValue"] = displayValue;
	}else{
		float value = [info[@"Glucose"] floatValue]/18+0.05;
		NSString *glucoseValue = [NSString stringWithFormat:@"%d.%d",(int)value,((int)(value*10)%10)];
		info[@"displayValue"] = glucoseValue;
	}
	
	return [info copy];
}



/** 发送数据 */
-(void)sendData:(NSData *)data{
	[_peripheral writeValue:data forCharacteristic:_sendCharacteristic type:CBCharacteristicWriteWithoutResponse];
}

/** 得到设备显示名字 */
-(NSString *)getDeviceDisplayName{
	return displayName;
}


@end
