蓝牙iOS

(转)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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容