(转)http://blog.sina.com.cn/s/blog_147d0371c0102vzut.html
项目源码
import
@protocol connectDeviceDelegate <<span style="color: rgb(52, 149, 175);">NSObject>
- (void)refreshView:(NSInteger)type;
@end
@interface DataCollectViewController : UIViewController
@property(nonatomic,assign)UINavigationController *nav;
@property(nonatomic,assign)id delegate;
@property (nonatomic, weak) id <<span style="color: rgb(52, 149, 175);">connectDeviceDelegate> connectDelegate;
@end
-------------------------------------------------- 分割线 ------
import "DataCollectViewController.h"
import
import "BLECtl.h"
import "Constants.h"
import "AppUtilities.h"
import "CharacteristicReader.h"
@interface DataCollectViewController ()<</span>CBCentralManagerDelegate,CBPeripheralDelegate,BLECtlDelegate,UIAlertViewDelegate>
{
CBUUID *bpmServiceUUID;
CBUUID *bpmBloodPressureMeasurementCharacteristicUUID;
CBUUID *bpmIntermediateCuffPressureCharacteristicUUID;
CBUUID *batteryServiceUUID;
CBUUID *batteryLevelCharacteristicUUID;
__weak IBOutlet UIButton *setBtn;
__weak IBOutlet UIButton *clearBtn;
__weak IBOutlet UIButton *saveBtn;
__weak IBOutlet UIButton *kongBtn;
__weak IBOutlet UIButton *canBtn;
__weak IBOutlet UILabel *titleLB;
__weak IBOutlet UITextField *highTF;
__weak IBOutlet UITextField *lowTF;
__weak IBOutlet UITextField *pulseTF;
__weak IBOutlet UITextField *sugarTF;
__weak IBOutlet UITextField *tempuratureTF;
__weak IBOutlet UIView *personsView;
__weak IBOutlet UITableView *personTV;
__weak IBOutlet UIScrollView *contentView;
NSString *bloodId;
NSString *sugarId;
NSString *gluType;
NSMutableArray *personList;
}
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *discoveredBloodPeripheral;
@property (nonatomic, strong) CBPeripheral *discoveredSugarPeripheral;
@property (nonatomic, weak) NSTimer *connectTimer;//重新连接血糖仪的定时器
@property (nonatomic, assign) BOOL isFirstConnectSuger;
@property (nonatomic, assign) BOOL isConnectedBlood;
@property (nonatomic, assign) BOOL isConnectedSugar;
@property (nonatomic, strong) NSThread *bloodThread;
@property (nonatomic, strong) NSThread *sugarThread;
@end
@implementation DataCollectViewController
@synthesize delegate,nav;
-
(void)viewDidLoad
{
[super viewDidLoad];saveBtn.layer.cornerRadius = 5.0;
gluType = @"1";
titleLB.userInteractionEnabled=YES;
UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(titleTab)];
[titleLB addGestureRecognizer:labelTapGestureRecognizer];
//titleLB.text = [NSString stringWithFormat:@"数据采集—%@",[UserEntity sharedUser].UserName];[personTV setSeparatorStyle:NO];
personList = [[NSMutableArray alloc] init];bloodId = [[NSUserDefaults standardUserDefaults] objectForKey:@"bloodidentifier"];
sugarId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sugaridentifier"];if ([bloodId isEqualToString:@""]||[sugarId isEqualToString:@""]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先移步系统设置中绑定设备!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
alertView.tag = 1001;
[alertView show];
}else{
[self initBluetooth];
}
}
//初始化蓝牙相关信息
-(void)initBluetooth
{
bpmServiceUUID = [CBUUID UUIDWithString:bpmServiceUUIDString];
bpmBloodPressureMeasurementCharacteristicUUID = [CBUUID UUIDWithString:bpmBloodPressureMeasurementCharacteristicUUIDString];
bpmIntermediateCuffPressureCharacteristicUUID = [CBUUID UUIDWithString:bpmIntermediateCuffPressureCharacteristicUUIDString];
batteryServiceUUID = [CBUUID UUIDWithString:batteryServiceUUIDString];
batteryLevelCharacteristicUUID = [CBUUID UUIDWithString:batteryLevelCharacteristicUUIDString];
self.isConnectedBlood = NO;
self.isConnectedSugar = NO;
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
//开始查看服务,蓝牙开启
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (central.state != CBCentralManagerStatePoweredOn){
return;
}
[self scanForDevice];
}
//搜索蓝牙设备
- (void)scanForDevice
{
NSLog(@"开始搜索");
[self.centralManager scanForPeripheralsWithServices:nil
options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
}
//查到外设后,启动线程连接设备
-
(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(@"发现设备%@", peripheral);NSString *name = peripheral.name;
if (name.length>=19&&[[name substringToIndex:19] isEqualToString:@"Yuwell BloodPressur"]&&self.isConnectedBlood==NO) {
NSLog(@"1 thread start,连接血压");
self.discoveredBloodPeripheral = peripheral;
_bloodThread=[[NSThread alloc]initWithTarget:self selector:@selector(conn:) object:peripheral];
[_bloodThread start];
self.isConnectedBlood = YES;
}
if ([name isEqual:@"Sinocare"]&&self.isConnectedSugar==NO) {
NSLog(@"2 thread start,连接血糖");
self.discoveredSugarPeripheral = peripheral;
_sugarThread=[[NSThread alloc]initWithTarget:self selector:@selector(conn:) object:peripheral];
[_sugarThread start];
self.isConnectedSugar = YES;
}
}
- (void)conn:(CBPeripheral *)peripheral
{
[self.centralManager connectPeripheral:peripheral options:nil];
NSLog(@"已连接%@", peripheral);
}
//连接外设成功,开始发现服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
if (peripheral.name.length>=19&&[[peripheral.name substringToIndex:19] isEqualToString:@"Yuwell BloodPressur"]){
self.isConnectedBlood = YES;
peripheral.delegate = self;
[peripheral discoverServices:nil];
}else if ([peripheral.name isEqualToString:@"Sinocare"]){
self.isFirstConnectSuger = YES;//记录第一次连接血糖仪的标志位
self.isConnectedSugar = YES;
peripheral.delegate = self;
[peripheral discoverServices:nil];
}
}
//连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"连接失败%@.(%@)", peripheral, [error localizedDescription]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"连接设备失败,请重新连接" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
alertView.tag = 1000;
[alertView show];
[self cleanup];
}
//已发现服务
-
(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (error){
NSLog(@"Error discovering services: %@", [error localizedDescription]);
[self cleanup];
return;
}for (CBService *service in peripheral.services){
[peripheral discoverCharacteristics:nil forService:service];
}
}
//已搜索到Characteristics
-
(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error){
NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
[self cleanup];
return;
}for (CBCharacteristic *characteristic in service.characteristics){
// [peripheral readValueForCharacteristic:characteristic];
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
-
(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error){
NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
return;
}if (peripheral.name.length>=19&&[[peripheral.name substringToIndex:19] isEqualToString:@"Yuwell BloodPressur"]){
NSData *data = characteristic.value;
uint8_t array = (uint8_t) data.bytes;if ([characteristic.UUID isEqual:bpmBloodPressureMeasurementCharacteristicUUID] || [characteristic.UUID isEqual:bpmIntermediateCuffPressureCharacteristicUUID]) { UInt8 flags = [CharacteristicReader readUInt8Value:&array]; BOOL pulseRatePresent = (flags & 0x04) > 0; if ([characteristic.UUID isEqual:bpmBloodPressureMeasurementCharacteristicUUID]){ float systolicValue = [CharacteristicReader readSFloatValue:&array]; float diastolicValue = [CharacteristicReader readSFloatValue:&array]; array += 2; highTF.text = [NSString stringWithFormat:@"%.0f", systolicValue]; lowTF.text = [NSString stringWithFormat:@"%.0f", diastolicValue]; }else{ array += 6; highTF.text = @""; lowTF.text = @""; } array += 7; if (pulseRatePresent){ float pulseValue = [CharacteristicReader readSFloatValue:&array]; pulseTF.text = [NSString stringWithFormat:@"%.0f", pulseValue]; }else{ pulseTF.text = @""; } } self.isConnectedBlood = NO; [_bloodThread cancel];
}else if ([peripheral.name isEqualToString:@"Sinocare"]){
if (characteristic.value.length > 12)
{
[self sugerDecodeFromStringData:[NSString stringWithFormat:@"%@",characteristic.value]];
}
self.isConnectedSugar = NO;
[_sugarThread cancel];
}
} -
(void)sugerDecodeFromStringData:(NSString *)stringData
{
if (stringData.length > 12){
NSRange range = NSMakeRange(28,2);
if (stringData){
long num = strtoul([[stringData substringWithRange:range] UTF8String], 0, 16);NSMutableString *data = [NSMutableString stringWithFormat:@"%.1f",num/10.0]; sugarTF.text = data; }
}
} -
(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"Peripheral Disconnected");if (peripheral.name.length>=19&&[[peripheral.name substringToIndex:19] isEqualToString:@"Yuwell BloodPressur"]){
self.discoveredBloodPeripheral = nil;
self.isConnectedBlood = NO;
[_bloodThread cancel];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"与设备断开连接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
alertView.tag = 1001;
[alertView show];
}else if ([peripheral.name isEqualToString:@"Sinocare"]){
if (!self.isFirstConnectSuger)//第二次连接后主动断开连接的弹框
{
self.discoveredSugarPeripheral = nil;
self.isConnectedSugar = NO;
[_sugarThread cancel];
[self.connectTimer invalidate];
self.connectTimer = nil;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"与设备断开连接" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
alertView.tag = 1001;
[alertView show];
}else//第一次断开连接后起定时器进行重新连接血糖仪
{
[self startTimer];
}
}
} (void)startTimer
{
self.isFirstConnectSuger = NO;
self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(startConnect) userInfo:nil repeats:NO];
}(void)startConnect
{
[self.centralManager connectPeripheral:self.discoveredSugarPeripheral options:nil];
}-
(void)cleanup
{
if (self.discoveredBloodPeripheral.state == CBPeripheralStateConnected){
if (self.discoveredBloodPeripheral.services != nil){
for (CBService *service in self.discoveredBloodPeripheral.services)
{
if (service.characteristics != nil)
{
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF4"]])
{
if (characteristic.isNotifying)
{
[self.discoveredBloodPeripheral setNotifyValue:NO forCharacteristic:characteristic];
return;
}
}
}
}
}
}
self.isConnectedBlood = NO;
[self.centralManager cancelPeripheralConnection:self.discoveredBloodPeripheral];
[_bloodThread cancel];
}if (self.discoveredSugarPeripheral.state == CBPeripheralStateConnected){
if (self.discoveredSugarPeripheral.services != nil){
for (CBService *service in self.discoveredSugarPeripheral.services)
{
if (service.characteristics != nil)
{
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"0xFFF4"]])
{
if (characteristic.isNotifying)
{
[self.discoveredSugarPeripheral setNotifyValue:NO forCharacteristic:characteristic];
return;
}
}
}
}
}
}
self.isConnectedSugar = NO;
[self.centralManager cancelPeripheralConnection:self.discoveredSugarPeripheral];
[_sugarThread cancel];
}
} (void)alertView:(UIAlertView *)alertView clickeonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1000 && buttonIndex == 1){
[self scanForDevice];
}
}(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//清空
- (IBAction)clearBtnPressed:(id)sender
{
highTF.text=@"";
lowTF.text=@"";
pulseTF.text=@"";
sugarTF.text=@"";
tempuratureTF.text=@"";
}
//保存
-
(IBAction)saveBtnPressed:(id)sender
{
[self.view endEditing:YES];BOOL warning = NO;
NSString *errMsg = @"";if ([highTF.text isEqual:@""]&&[lowTF.text isEqual:@""]&&[pulseTF.text isEqual:@""]&&[sugarTF.text isEqual:@""]&&[tempuratureTF.text isEqual:@""]) {
warning = YES;
errMsg = @"未采集数据!";
}if (warning) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:errMsg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
return;
}NSDictionary *recordEntity = @{
@"sbp":highTF.text,
@"dbp":lowTF.text,
@"pulseRate":pulseTF.text,
@"fbg":sugarTF.text,
@"gluType":gluType,
@"temperature":tempuratureTF.text,
@"bpEquipNo":@"",
@"bsEquipNo":@"",
@"teEquipNo":@""};NSData *data = [NSJSONSerialization dataWithJSONObject:recordEntity options:NSJSONWritingPrettyPrinted error:nil];
NSString *saveData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];NSDictionary *params = @{@"clacDataInfo":saveData};
}
//选择空腹
- (IBAction)kongBtnPressed:(UIButton *)sender
{
kongBtn.selected = YES;
canBtn.selected = NO;
gluType = @"1";
}
//选择餐后2小时
- (IBAction)canBtnPressed:(UIButton *)sender
{
kongBtn.selected = NO;
canBtn.selected = YES;
gluType = @"2";
}
//点击空白处隐藏人员页面
- (IBAction)coverBtnPressed:(id)sender
{
personsView.hidden = YES;
}
- (BOOL)matchByRegex:(NSString *)regex input:(NSString *)input
{
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
return [pred evaluateWithObject:input];
}
-(BOOL)isTrue:(UITextField *)textField replacementString:(NSString *)string charRange:(NSRange)range
{
BOOL isHaveDian = YES;
if ([textField.text rangeOfString:@"."].location==NSNotFound) {
isHaveDian=NO;
}
if ([string length]>0){
unichar single=[string characterAtIndex:0];//当前输入的字符
if ((single >='0' && single<='9') || single=='.')//数据格式正确
{
//首字母不能为小数点
if([textField.text length]==0&&single=='.'){
return NO;
}
//在最前端不能插入.
if ([textField.text length]>0&&range.location==0&&single == '.') {
return NO;
}
if (single=='.'){
if(!isHaveDian){
isHaveDian=YES;
return YES;
}else{
return NO;
}
}else{
if (isHaveDian){
//小数点的位数
NSRange ran=[textField.text rangeOfString:@"."];
if(range.location>ran.location){
NSUInteger tt=[textField.text length]-1-ran.location;
if (tt < 1){
return YES;
}else{
return NO;
}
}else{
if(ran.location< 2){
return YES;
}else{
return NO;
}
}
}else{
if([textField.text length]<2){
return YES;
}else{
return NO;
}
}
}
}else{//输入的数据格式不正确
return NO;
}
}else{
return YES;
}
}
(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField == sugarTF){
[contentView setContentOffset:CGPointMake(0, 60) animated:YES];
}else if (textField == tempuratureTF){
[contentView setContentOffset:CGPointMake(0, 100) animated:YES];
}
return YES;
}(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == highTF) {
[lowTF becomeFirstResponder];
}else if (textField == lowTF){
[pulseTF becomeFirstResponder];
}else if (textField == pulseTF){
[sugarTF becomeFirstResponder];
}else if (textField == sugarTF){
[tempuratureTF becomeFirstResponder];
}else if (textField == tempuratureTF){
[self.view endEditing:YES];
[contentView setContentOffset:CGPointMake(0, 0) animated:YES];
}
return YES;
}(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
[contentView setContentOffset:CGPointMake(0, 0) animated:YES];
}(IBAction)swipeLeft:(id)sender{
[self setBtnPressed:nil];
}
@end