藍牙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:@"請先移步系統(tǒng)設置中綁定設備!" 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(@"發(fā)現設備%@", 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);
    }

//連接外設成功,開始發(fā)現服務

  • (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];
    }

//已發(fā)現服務

  • (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];
    }
    }

//獲取外設發(fā)來的數據,不論是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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,963評論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 99,348評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,083評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,706評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,442評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,802評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,795評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,983評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 49,542評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,287評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,486評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,030評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,710評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,116評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,412評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,224評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,462評論 2 378

推薦閱讀更多精彩內容