// // SearchDevicePage.m // pregnancy_guard // // Created by WindShan on 2017/7/11. // Copyright © 2017年 WindShan. All rights reserved. // #import "SearchDevicePage.h" #import "GloriaLabel.h" #import "SearchDeviceCell.h" #import "DevicesTableViewCell.h" #import "BaseNaviController.h" #import "ProgressHandler.h" #import "UIView+Toast.h" #import "UIImage+animatedGIF.h" #import "SearchTipsCell.h" @interface SearchDevicePage () { BOOL isBluetoothON; UIButton* ic_search_btn; UIImageView * ic_search_done; UIImageView * ic_searching; CGFloat ic_top_bkH; CGFloat ic_search_doneH; GloriaLabel* _TitleLabel; GloriaLabel* _SetTitleLabel; } @property (nonatomic, strong) UITableView * tableView; @property (nonatomic, assign) int currentStatus; // 0 初始化 1 检索中 2 检索完成 @end @implementation SearchDevicePage - (UITableView *)tableView { if (!_tableView) { _tableView = [[UITableView alloc] init]; _tableView.delegate = self; _tableView.dataSource = self; //_tableView.separatorColor = [UIColor clearColor]; [self.view addSubview:_tableView]; [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(UIEdgeInsetsMake(ic_top_bkH , 0, 0, 0)); }]; _tableView.tableFooterView = [UIView new]; } return _tableView; } -(void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [[CBMoralManager sharedManager] disconnectPeripheral:[[CBMoralManager sharedManager] myPeripheral]]; } // 返回设备数目 //if (isBluetoothON) { // return [[[CBMoralManager sharedManager] foundPeripherals] count]; //} -(void)viewDidDisappear:(BOOL)animated { [[CBMoralManager sharedManager]stopScanning]; } -(void)startScanning { // Start scanning for devices [[CBMoralManager sharedManager] startScanning]; [self performSelector:@selector(stopScanning) withObject:nil afterDelay:5.0f]; } -(void)pullToRefresh { [[CBMoralManager sharedManager] refreshPeripherals]; [self performSelector:@selector(stopScanning) withObject:nil afterDelay:5.0f]; } -(void)stopScanning { if([[[CBMoralManager sharedManager] foundPeripherals] count] == 0) { self.currentStatus = 0; [self.tableView reloadData]; } ic_search_done.hidden = NO; ic_searching.hidden = YES; [ic_search_btn setBackgroundImage:[UIImage imageNamed:@"ic_search_start_btn" ] forState:UIControlStateNormal]; [[CBMoralManager sharedManager]stopScanning]; //[self.tableView.header endRefreshing]; } - (void)viewDidLoad { [super viewDidLoad]; self.title = @"设备检索"; [self setNavigationLeft:@"ic_back_arraw.png" sel:@selector(backAticon)]; self.currentStatus = 0; ic_top_bkH = 325; ic_search_doneH = 230; if ( IsiPhone4 || IsiPhone5 ) { ic_top_bkH = 260; ic_search_doneH = 180; } UIImageView * ic_top_bk = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ic_top_bkH)]; ic_top_bk.image = [UIImage imageNamed:@"ic_top_bk"]; [self.view addSubview:ic_top_bk]; ic_search_done = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ic_top_bkH)]; ic_search_done.image = [UIImage imageNamed:@"ic_search_done"]; [self.view addSubview:ic_search_done]; ic_searching = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ic_top_bkH)]; [ic_searching setImage:[UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource:@"gif_searching" withExtension:@"gif"]]]; [self.view addSubview:ic_searching]; ic_searching.hidden = YES; ic_search_btn = [UIButton buttonWithType:UIButtonTypeCustom]; ic_search_btn.frame = CGRectMake((SCREEN_WIDTH-128)/2, ic_search_doneH+55, 128, 32); [ic_search_btn setBackgroundImage:[UIImage imageNamed:@"ic_search_start_btn" ] forState:UIControlStateNormal]; ic_search_btn.titleLabel.font = [UIFont systemFontOfSize: 18.0]; ic_search_btn.layer.masksToBounds=YES; ic_search_btn.layer.cornerRadius=8.0f; [ic_search_btn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:ic_search_btn]; self.tableView.hidden = NO; // Do any additional setup after loading the view. [[CBMoralManager sharedManager] setCbDiscoveryDelegate:self]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { if (_currentStatus == 2) { return 2; } else return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (_currentStatus == 2 && isBluetoothON ) { if(section == 0) { return 1; } else return [[[CBMoralManager sharedManager] foundPeripherals] count]; } else return 5; } //此处上面和下面 是设置 footerview - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (_currentStatus != 2) { NSUInteger index = [indexPath row]; if(index == 0 ) { NSString *CellIdentifier = @"searchTipsCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; } if(_SetTitleLabel==nil) { _SetTitleLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(10, 6,SCREEN_WIDTH/2, 30)]; _SetTitleLabel.font = [UIFont systemFontOfSize:14]; _SetTitleLabel.textAlignment = UITextAlignmentLeft; _SetTitleLabel.textColor = kUIColorFromRGB(0x595959); [cell.contentView addSubview:_SetTitleLabel]; } _SetTitleLabel.text = @"操作设置步骤"; return cell; } else { NSString *CellIdentifier = @"searchTips2Cell"; SearchTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[SearchTipsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; } switch (index) { case 1: { [cell setItemView:@"打开孕哨设备电源开关" imgName:@"icon_one"]; } break; case 2: { [cell setItemView:@"打开手机蓝牙" imgName:@"icon-two"]; } break; case 3: { [cell setItemView:@"点击APP按钮[开始搜索设备]" imgName:@"icon-three"]; } break; case 4: { [cell setItemView:@"搜索完毕,点击对应蓝牙列表,自动匹配" imgName:@"icon-four"]; } break; } return cell; } } else { NSUInteger section = [indexPath section]; if(section==0) { NSString *CellIdentifier = @"searchDeviceCell1"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; } if( _TitleLabel == nil) { _TitleLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(20, 15,SCREEN_WIDTH/2, 20)]; _TitleLabel.font = [UIFont systemFontOfSize:14]; _TitleLabel.textAlignment = UITextAlignmentLeft; _TitleLabel.textColor = kUIColorFromRGB(0x595959); _TitleLabel.text = @"蓝牙列表"; [cell.contentView addSubview:_TitleLabel]; } return cell; } else if(section==1) { NSString *CellIdentifier = @"searchDeviceCell"; SearchDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[SearchDeviceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; } CBPeripheralExt *newPeriPheral = [[[CBMoralManager sharedManager] foundPeripherals] objectAtIndex:indexPath.row]; NSString * bleName = [self nameForPeripheral:newPeriPheral]; NSString * bleUUID = [self UUIDStringfromPeripheral:newPeriPheral]; NSString * bleService = [self ServiceCountfromPeripheral:newPeriPheral]; [cell setItemView:bleName]; //[cell setDiscoveredPeripheralDataFromPeripheral:newPeriPheral]; return cell; } } return nil; } /*! * @method nameForPeripheral: * * @discussion Method to get the peripheral name * */ -(NSString *)nameForPeripheral:(CBPeripheralExt *)ble { NSString *bleName ; if ([ble.mAdvertisementData valueForKey:CBAdvertisementDataLocalNameKey] != nil) { bleName = [ble.mAdvertisementData valueForKey:CBAdvertisementDataLocalNameKey]; } if(bleName.length < 1 ) bleName = ble.mPeripheral.name; if(bleName.length < 1 ) bleName = UNKNOWN_PERIPHERAL; return bleName; } /*! * @method UUIDStringfromPeripheral: * * @discussion Method to get the UUID from the peripheral * */ -(NSString *)UUIDStringfromPeripheral:(CBPeripheralExt *)ble { NSString *bleUUID = ble.mPeripheral.identifier.UUIDString; if(bleUUID.length < 1 ) bleUUID = @"Nil"; else bleUUID = [NSString stringWithFormat:@"%@",bleUUID]; return bleUUID; } /*! * @method ServiceCountfromPeripheral: * * @discussion Method to get the number of services present in a device * */ -(NSString *)ServiceCountfromPeripheral:(CBPeripheralExt *)ble { NSString *bleService =@""; NSInteger serViceCount = [[ble.mAdvertisementData valueForKey:CBAdvertisementDataServiceUUIDsKey] count]; if(serViceCount < 1 ) bleService = @"No Services"; else bleService = [NSString stringWithFormat:@" %ld Service Advertised ",(long)serViceCount]; return bleService; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ if (_currentStatus == 2) { NSInteger index = [indexPath row]; if (isBluetoothON) { [tableView deselectRowAtIndexPath:indexPath animated:YES]; [self connectPeripheral:indexPath.row]; } // DeviceSpareModel* model = [self.modelArray objectAtIndex:index]; // 跳转酒店备用界面 //HotelSelPage* page = [[HotelSelPage alloc] initIsFirstPage:NO]; //page.bSelRoom = 2; // 跳转界面 //BaseNaviController *baseNav = [[BaseNaviController alloc] initWithRootViewController:page]; //[self presentViewController:baseNav animated:YES completion:nil]; //[self showActionForPhoto]; } } /** *This method invoke after a new peripheral found. */ -(void)discoveryDidRefresh { _currentStatus = 2; [self.tableView reloadData]; } #pragma mark - BlueTooth Turned Off Delegate /*! * @method bluetoothStateUpdatedToState: * 蓝牙状态判断 * @discussion Method to be called when state of Bluetooth changes * */ -(void)bluetoothStateUpdatedToState:(BOOL)state { isBluetoothON = state; [self.tableView reloadData]; isBluetoothON ? [self.tableView setScrollEnabled:YES] : [self.tableView setScrollEnabled:NO]; } #pragma mark - Connect /*! * @method connectPeripheral: * * @discussion Method to connect the selected peripheral * */ -(void)connectPeripheral:(NSInteger)index { if ([[CBMoralManager sharedManager] foundPeripherals].count != 0) { CBPeripheralExt *selectedBLE = [[[CBMoralManager sharedManager] foundPeripherals] objectAtIndex:index]; [[ProgressHandler sharedInstance] showWithDetailsLabel:@"Connecting.." Detail:selectedBLE.mPeripheral.name]; [[CBMoralManager sharedManager] connectPeripheral:selectedBLE.mPeripheral CompletionBlock:^(BOOL success, NSError *error) { [[ProgressHandler sharedInstance] hideProgressView]; if(success) { _bConnectSuccess = YES; NSString * bleName = [self nameForPeripheral:selectedBLE]; NSString * bleUUID = [self UUIDStringfromPeripheral:selectedBLE]; [UserDefault setObject:bleUUID forKey:@"bleUUID"]; [UserDefault setObject:bleName forKey:@"bleName"]; [UserDefault synchronize];//使用synchronize强制立即将数据写入磁盘,防止在写完NSUserDefaults后程序退出导致的数据丢失 //CBPeripheralExt *selBLE = [UserDefault objectForKey:@"Peripheral"];//根据键值取出Peripheral [self backAticon]; } else { if(error) { NSString *errorString = [error.userInfo valueForKey:NSLocalizedDescriptionKey]; if(errorString.length) { [self.view makeToast:errorString]; } else { [self.view makeToast:UNKNOWN_ERROR]; } } } }]; } else { NSLog(@"Array is nil"); [[CBMoralManager sharedManager] refreshPeripherals]; } } -(void)searchAction { self.currentStatus = 1; ic_search_done.hidden = YES; ic_searching.hidden = NO; //[mainImageView setImage:[UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource:imageName withExtension:@"gif"]]]; [ic_search_btn setBackgroundImage:[UIImage imageNamed:@"ic_search_stop_btn"] forState:UIControlStateNormal]; [self startScanning]; } -(void)backAticon { //[self.navigationController popToViewController:self animated:YES]; [self dismissViewControllerAnimated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end