单军华
2018-04-18 de88ae127e305e0b153c327b073645f9353cace5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//
//  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"
#import <CoreBluetooth/CoreBluetooth.h>
 
@interface SearchDevicePage ()<UITableViewDelegate,UITableViewDataSource,CBCentralManagerDelegate>
{
    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 检索完成
@property (nonatomic, strong) CBCentralManager              * centralManager;
@end
 
 
 
@implementation SearchDevicePage
 
//-(CBCentralManager *)centralManager
//{
//    if (_centralManager == nil) {
//        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
//    }
//    return _centralManager;
//}
 
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOff:
        {
            //[mainView makeToast:@"蓝牙没有开启,在设置中打开蓝牙"];
            [Global alertMessageEx:@"蓝牙没有开启,在设置中打开蓝牙功能" title:@"温馨提示" okTtitle:nil cancelTitle:@"OK" delegate:self];
        }
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@"蓝牙设备开着");
            break;
        case CBCentralManagerStateResetting:
            break;
        case CBCentralManagerStateUnauthorized:
            break;
        case CBCentralManagerStateUnknown:
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"当前设备不支持蓝牙");
            [Global alertMessageEx:@"很抱歉,当前设备不支持蓝牙" title:@"温馨提示" okTtitle:nil cancelTitle:@"OK" delegate:self];
            break;
        default:
            break;
    }
}
 
- (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;
    CGFloat btnSearchH = 55;
    if ( IsiPhone4 || IsiPhone5 )
    {
        ic_top_bkH = 260;
        ic_search_doneH = 180;
        btnSearchH = 40;
    }
    
    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+btnSearchH, 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.
    
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
    
    [[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