单军华
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//
//  RadiaDetectionPage.m
//  pregnancy_guard
//
//  Created by WindShan on 2017/7/5.
//  Copyright © 2017年 WindShan. All rights reserved.
//
 
#import "RadiaDetectionPage.h"
#import "ASValueTrackingSlider.h"
 
#import "ZZCircleProgress.h"
#import "GloriaLabel.h"
#import "CBPeripheralExt.h"
#import "MBleService.h"
#import "Constants.h"
#import "UIView+Toast.h"
#import "CBMoralManager.h"
#import "BaseNaviController.h"
#import "HistoryRecordPage.h"
#import "NetworkSingleton.h"
#import "UploadModel.h"
#import "NetworkSingleton.h"
#import "SearchDevicePage.h"
 
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import<BaiduMapAPI_Search/BMKPoiSearchType.h>
#import "DataModel.h"
 
@interface RadiaDetectionPage ()<ASValueTrackingSliderDelegate,ASValueTrackingSliderDataSource,cbCharacteristicManagerDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate>
{
    ZZCircleProgress *circle3;
    CGFloat gaugeValue;
    CGFloat gaugeAngle;
    UIImageView * ic_pointer;
    CGFloat maxNum;
    CGFloat minNum;
    
    CGFloat maxAngle;
    CGFloat minAngle;
    CGFloat angleperValue;
    
    BOOL notifyEnable;
    BOOL hexSend;
    CBCharacteristic *notifyCharacteristic;
    CBCharacteristic *writeCharacteristic;
    CBCharacteristic *readCharacteristic;
    void(^characteristicWriteCompletionHandler)(BOOL success,NSError *error);
    
    BOOL isBluetoothON;
    
    UIImageView * ic_anquan_status;
    int deviceStstaus; //0 未连接 1 已连接 2 检测中 3 连接中
    GloriaLabel* deviceStatusLabel;
    GloriaLabel* _JiliangNumLabel;
    GloriaLabel* _BiaozhunJiliangNumLabel;
    GloriaLabel* _currentShuziTipsLabel;
    GloriaLabel* _currentTipsLabel;
    
    NSArray *characteristicArray;
    NSString *bleCurrentUUID;
    NSString *receiveHexValue;
    
    ASValueTrackingSlider * _trackingSlider;
    
    // 定位
    //BMKMapView* _mapView;
    BMKLocationService* _locService;
    NSString * address;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    
    NSMutableArray *  dataModelArr;
    NSTimer * myTimer;
    NSString * myTimeInterval;
    NSString * is_open_upload; // 1 可以 0 禁止
    
    GloriaLabel* _AnquanStatustLabel;
    UIImageView * icon_anquan;
    UIImageView * ic_zhishu_bk;
    UIImageView * ic_weixin_tips;
}
@end
 
 
@implementation RadiaDetectionPage
 
-(void) getcharcteristicsForService:(CBService *)service
{
    [[CBMoralManager sharedManager] setCbCharacteristicDelegate:self];
    [[[CBMoralManager sharedManager] myPeripheral] discoverCharacteristics:nil forService:service];
}
 
-(NSMutableArray *) getPropertiesForCharacteristic:(CBCharacteristic *)characteristic
{
    
    NSMutableArray *propertyList = [NSMutableArray array];
    
    if ((characteristic.properties & CBCharacteristicPropertyRead) != 0)
    {
        [propertyList addObject:READ];
    }
    if (((characteristic.properties & CBCharacteristicPropertyWrite) != 0) || ((characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) != 0) )
    {
        [propertyList addObject:WRITE];;
    }
    if ((characteristic.properties & CBCharacteristicPropertyNotify) != 0)
    {
        [propertyList addObject:NOTIFY];;
    }
    if ((characteristic.properties & CBCharacteristicPropertyIndicate) != 0)
    {
        [propertyList addObject:INDICATE];
    }
    
    return propertyList;
}
 
-(NSString *)getPropertiesText:(NSMutableArray *) characteristicProperties{
    NSString *property = @"";
    
    if (characteristicProperties != nil)
    {
        if (characteristicProperties.count > 0)
        {
            property = [characteristicProperties objectAtIndex:0];
        }
        
        for (int i= 1; i < characteristicProperties.count; i++)
        {
            property = [property stringByAppendingString:[NSString stringWithFormat:@" & %@",[characteristicProperties objectAtIndex:i]]];
        }
        
    }
    
    return property;
}
 
-(NSMutableArray *)getUsrDebugModeProperties
{
    NSMutableArray *propertyList = [NSMutableArray array];
    [propertyList addObject:NOTIFY];
    [propertyList addObject:WRITE];
    return propertyList;
}
 
 
#pragma mark - CBCharacteristicManagerDelegate
 
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if ([service.UUID isEqual:[[CBMoralManager sharedManager] myService].UUID]){
        characteristicArray = [service.characteristics copy];
        
        
        NSString *property = [self getPropertiesText:[self getPropertiesForCharacteristic:[characteristicArray objectAtIndex:0]]];
        
        if ([property isEqualToString: NOTIFY])
        {
            [[CBMoralManager sharedManager] setMyCharacteristic:[characteristicArray objectAtIndex:0]];
            [[CBMoralManager sharedManager] setMyCharacteristic2:[characteristicArray objectAtIndex:1]];
        }else{
            [[CBMoralManager sharedManager] setMyCharacteristic:[characteristicArray objectAtIndex:1]];
            [[CBMoralManager sharedManager] setMyCharacteristic2:[characteristicArray objectAtIndex:0]];
        }
        
        [[CBMoralManager sharedManager] setCharacteristicProperties:[self getUsrDebugModeProperties]];
        
        notifyCharacteristic = [[CBMoralManager sharedManager]myCharacteristic];
        readCharacteristic = [[CBMoralManager sharedManager]myCharacteristic];
        writeCharacteristic = [[CBMoralManager sharedManager]myCharacteristic2];
 
        [self notifyOption];
        
        deviceStstaus = 2;
        deviceStatusLabel.text = @"检测中";
        if (myTimer == nil)
            myTimer =  [NSTimer scheduledTimerWithTimeInterval:[myTimeInterval doubleValue] target:self selector:@selector(data_upload) userInfo:nil repeats:YES];
        else
            //开启定时器
            [myTimer setFireDate:[NSDate distantPast]];
        //每myTimeInterval秒运行一次data_upload方法。
    }
}
 
 
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if ([characteristic.UUID isEqual:[[CBMoralManager sharedManager] myCharacteristic].UUID])
    {
        // Show descriptor button only when descriptors exist for the characteristic
        if (characteristic.descriptors.count > 0)
        {
            [[CBMoralManager sharedManager] setCharacteristicDescriptors:characteristic.descriptors];
            // do somethis
        }
    }
}
 
/*!
 *@Method Notify Read Indicate options result return
 * 蓝牙消息监听回调
 */
-(void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if ([characteristic.UUID isEqual:[[CBMoralManager sharedManager] myCharacteristic].UUID])
    {
        receiveHexValue = [Utilities bytesToHex:characteristic.value];
        
        if( receiveHexValue.length == 40 )
        {
            //16进制转10进制
           NSString * shishiStr = [receiveHexValue substringWithRange:NSMakeRange(24,4)];
           NSString * leijiStr = [receiveHexValue substringWithRange:NSMakeRange(28,8)];
            
           NSString * shishiValue = [NSString stringWithFormat:@"%lu",strtoul([shishiStr UTF8String],0,16)];
           NSString * leijiValue = [NSString stringWithFormat:@"%lu",strtoul([leijiStr UTF8String],0,16)];
          
           if( leijiValue.length >= 6)
           {
               _JiliangNumLabel.text = [NSString stringWithFormat:@"%.1f",[leijiValue floatValue]*0.10];
           }
            else
                _JiliangNumLabel.text = [NSString stringWithFormat:@"%.3f",[leijiValue floatValue]*0.10];
            
            _BiaozhunJiliangNumLabel.text = [NSString stringWithFormat:@"%.3f",([shishiValue floatValue]-45)/10.0*0.10];
            
            
            //dataModelArr
            DataModel * model = [[DataModel alloc]init];
            model.value = _BiaozhunJiliangNumLabel.text;
            model.time  = [DateUtil stringFromDateYMD:[NSDate date]];
            [dataModelArr addObject:model];
            
            circle3.progress = ([leijiValue floatValue]/FUSHE_MAX_VALUE)*100;
            [_trackingSlider setValue:circle3.progress];
            [self setGaugeValue:circle3.progress animation:NO];
            
 
            if( [shishiValue intValue] < FUSHE_SAFE_VALUE )
            {
                _currentShuziTipsLabel.text = @"当前位置安全";
                _currentTipsLabel.textColor = RgbColor(64, 159, 252);
                _currentTipsLabel.text = @"您所处位置辐射安全,\n 您处于安全区域,可以长时间逗留!";
            }
            else if ( [shishiValue intValue] < FUSHE_GOOD_VALUE)
            {
                _currentShuziTipsLabel.text = @"当前位置有轻微辐射";
                _currentTipsLabel.textColor = RgbColor(64, 159, 252);
                _currentTipsLabel.text = @"您所处位置辐射轻微,\n 不利于您的健康,请远离到安全区域!";
            }
            else if ( [shishiValue intValue] < FUSHE_CHA_VALUE)
            {
                _currentShuziTipsLabel.text = @"当前位置辐射超标";
                _currentTipsLabel.textColor = RgbColor(252, 80, 84);
                _currentTipsLabel.text = @"您所处位置辐射超标,\n 不利于您的健康,请远离到安全区域!";
            }
            else if ( [shishiValue intValue] < FUSHE_DANGER_VALUE)
            {
                _currentShuziTipsLabel.text = @"当前位置有较高辐射";
                _currentTipsLabel.textColor = RgbColor(252, 80, 84);
                _currentTipsLabel.text = @"您所处位置辐射偏高,\n 不利于您的健康,请远离到安全区域!";
            }
            else if ( [shishiValue intValue] < FUSHE_MAX_VALUE)
            {
                _currentShuziTipsLabel.text = @"当前位置有很高辐射";
                _currentTipsLabel.textColor = RgbColor(252, 80, 84);
                _currentTipsLabel.text = @"您所处位置辐射偏高,\n 不利于您的健康,请远离到安全区域!";
            }
            else
            {
                _currentShuziTipsLabel.text = @"当前位置有很高辐射";
                _currentTipsLabel.textColor = RgbColor(252, 80, 84);
                _currentTipsLabel.text = @"您所处位置辐射很高,\n 不利于您的健康,请远离到安全区域!";
            }
            
        }
        
        //NSString *ASCIIValue = [[NSString alloc]initWithData:characteristic.value encoding:NSASCIIStringEncoding];
        
        //[self writeOption:hexValue];
        //MMessage *msg = [[MMessage alloc]initMessageWithString:[NSString stringWithFormat:@"%@ [ASCII:%@]",hexValue,ASCIIValue] Type:TYPE_RECEIVE];
        //[self displayMsg:msg];
    }
}
 
-(void) peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if ([characteristic.UUID isEqual:[[CBMoralManager sharedManager] myCharacteristic].UUID])
    {
        if (error == nil)
        {
            [Utilities logDataWithService:[ResourceHandler getServiceNameForUUID:[[CBMoralManager sharedManager] myService].UUID] characteristic:[ResourceHandler getCharacteristicNameForUUID:[[CBMoralManager sharedManager] myCharacteristic].UUID] descriptor:nil operation:[NSString stringWithFormat:@"%@- %@",WRITE_REQUEST_STATUS,WRITE_SUCCESS]];
            characteristicWriteCompletionHandler (YES,error);
            
        }
        else
        {
            [Utilities logDataWithService:[ResourceHandler getServiceNameForUUID:[[CBMoralManager sharedManager] myService].UUID] characteristic:[ResourceHandler getCharacteristicNameForUUID:[[CBMoralManager sharedManager] myCharacteristic].UUID] descriptor:nil operation:[NSString stringWithFormat:@"%@- %@%@",WRITE_REQUEST_STATUS,WRITE_ERROR,[error.userInfo objectForKey:NSLocalizedDescriptionKey]]];
            
            characteristicWriteCompletionHandler(NO,error);
        }
    }
}
 
#pragma mark---------option method
 
// 读取蓝牙消息
-(void)readOption
{
    //MMessage *msg = [[MMessage alloc]initMessageWithString:OPTION_READ Type:TYPE_SEND];
    //[self displayMsg:msg];
    [[[CBMoralManager sharedManager] myPeripheral] readValueForCharacteristic:readCharacteristic];
}
 
/*!
 *  @method writeButtonClicked :
 *
 *  @discussion Method to handle the write button click
 *  发送蓝牙消息
 */
- (void)writeOption:(NSString*)text
{
    
    //MMessage *msg = [[MMessage alloc]initMessageWithString:text Type:TYPE_SEND];
    //[self displayMsg:msg];
 
    NSData *dataToWrite;
    if (hexSend)
    {
        dataToWrite = [Utilities dataFromHexString:[text stringByReplacingOccurrencesOfString:@" " withString:@""]];
    }
    else
    {
        if ([text rangeOfString:@"AT+"].location != NSNotFound || [text rangeOfString:@"at+"].location != NSNotFound) {
            text = [text stringByAppendingString:@"\r\n"];
        }
        dataToWrite = [text dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    // Write data to the device
    [self writeDataForCharacteristic:writeCharacteristic  WithData:dataToWrite completionHandler:^(BOOL success, NSError *error) {
        if (success){
            //            ((MMessageFrame*)[msgArray objectAtIndex:msgArray.count-1]).message.isDone = YES;
            //            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:msgArray.count-1 inSection:0];
            //            [_msgTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            
        }else{
            NSLog(@"-------------->write text fail");
        }
    }];
    
    
    
}
 
 
/*!
 *  @method writeDataForCharacteristic: WithData:
 *
 *  @discussion Method to write data to the device
 *
 */
-(void) writeDataForCharacteristic:(CBCharacteristic *)characteristic WithData:(NSData *)data completionHandler:(void(^) (BOOL success, NSError *error))handler{
    characteristicWriteCompletionHandler = handler;
    if ((characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) != 0)
    {
        [[[CBMoralManager sharedManager] myPeripheral] writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
        characteristicWriteCompletionHandler (YES,nil);
        
    }else{
        [[[CBMoralManager sharedManager] myPeripheral] writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
}
 
 
 
/*!
 *  @method notifyButtonClicked:
 *  开始监听蓝牙消息
 *  @discussion Method to handle notify button click
 *
 */
 
- (void)notifyOption
{
    if (!notifyEnable)
    {
        notifyEnable = YES;
        
        //MMessage *msg = [[MMessage alloc]initMessageWithString:OPTION_NOTIFY Type:TYPE_SEND];
        //[self displayMsg:msg];
        
        //[_btnOption setTitle:OPTION_STOP_NOTIFY forState:UIControlStateNormal];
        [[[CBMoralManager sharedManager] myPeripheral] setNotifyValue:YES forCharacteristic:notifyCharacteristic];
        
    }
    else
    {
        notifyEnable = NO;
        
        //MMessage *msg = [[MMessage alloc]initMessageWithString:OPTION_STOP_NOTIFY Type:TYPE_SEND];
        //[self displayMsg:msg];
        
        //[_btnOption setTitle:OPTION_NOTIFY forState:UIControlStateNormal];
        [[[CBMoralManager sharedManager] myPeripheral] setNotifyValue:NO forCharacteristic:notifyCharacteristic];
    }
}
 
/*!
 *  @method UUIDArray:
 *
 *  @discussion Return all UUID as CBUUID
 *
 */
 
-(NSArray*)UUIDArray:(NSArray *)allService
{
    NSMutableArray *UUIDArray = [NSMutableArray array];
    for(NSString *string in allService)
    {
        [UUIDArray addObject:[CBUUID UUIDWithString:string]];
    }
    return (NSArray *)UUIDArray;
}
 
 
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
 
    //_mapView.delegate = nil; // 不用时,置nil
    _locService.delegate = nil;
    
    //关闭定时器
    if(myTimer)
        [myTimer setFireDate:[NSDate distantFuture]];
}
 
-(void)viewWillAppear:(BOOL)animated
{
    
    bleCurrentUUID = [UserDefault objectForKey:@"bleUUID"];
    NSString *bleName = [UserDefault objectForKey:@"bleName"];
    
    //_mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    _locService.delegate = self;
    
    if(bleCurrentUUID != nil)
    {
        if( _bConnectSuccess )
        {
            deviceStstaus = 1;
            deviceStatusLabel.text = @"已连接";
            
            // 连接成功设置服务
            NSArray *allService = [self UUIDArray:[[[CBMoralManager sharedManager] serviceUUIDDict] allKeys]];
            
            for(CBService *service in [[CBMoralManager sharedManager] foundServices])
            {
                if([allService containsObject:service.UUID] && [service.UUID.UUIDString isEqualToString:BLE_DEVICE_UUID])
                {
                    NSInteger ServiceKeyIndex = [allService indexOfObject:service.UUID];
                    CBUUID *keyID = [allService objectAtIndex:ServiceKeyIndex];
                    
                    NSString *name = [[[[CBMoralManager sharedManager] serviceUUIDDict] valueForKey:[keyID.UUIDString lowercaseString]] objectForKey:k_SERVICE_NAME_KEY];
                    MBleService *mbleService = [[MBleService alloc]initWithName:name Service:service uuid:keyID];
                    
                    [[CBMoralManager sharedManager] setMyService:mbleService.service];
                    
                    CBService *service = [[CBMoralManager sharedManager] myService];
                    
                    [self getcharcteristicsForService:service];
                    
                }
                //else
                //{
                //    CBUUID *unknowCBUUID = service.UUID;
                //    MBleService *mbleService = [[MBleService alloc]initWithName:@"Unknow Service" Service:service uuid:unknowCBUUID];
                //}
            }
        }
        else
        {
            // 检索设备是否存在
            //[[CBMoralManager sharedManager] disconnectPeripheral:[[CBMoralManager sharedManager] myPeripheral]];
            [[CBMoralManager sharedManager] setCbDiscoveryDelegate:self];
            [[CBMoralManager sharedManager] startScanning];
            [self performSelector:@selector(stopScanning) withObject:nil afterDelay:3.0f];
        }
        
    }
}
 
-(void)stopScanning
{
    [[CBMoralManager sharedManager]stopScanning];
}
 
#pragma mark - BlueTooth Turned Off Delegate
 
/*!
 *  @method bluetoothStateUpdatedToState:
 *
 *  @discussion Method to be called when state of Bluetooth changes
 *
 */
 
-(void)bluetoothStateUpdatedToState:(BOOL)state
{
    isBluetoothON = state;
    
    // 提示打开蓝牙设备
    
}
 
 
/**
 *This method invoke after a new peripheral found. 蓝牙检索成功 开始连接
 */
-(void)discoveryDidRefresh
{
    NSUInteger count = [[CBMoralManager sharedManager] foundPeripherals].count;
    if( count > 0)
    {
        for (NSUInteger i = 0; i < count; i++)
        {
            CBPeripheralExt *newPeriPheral = [[[CBMoralManager sharedManager] foundPeripherals] objectAtIndex:i];
            NSString * bleUUID = [self UUIDStringfromPeripheral:newPeriPheral];
            if( [bleUUID isEqualToString:bleCurrentUUID] )
            {
                [[CBMoralManager sharedManager]stopScanning];
                
                deviceStstaus = 3;
                deviceStatusLabel.text = @"连接中";
                
                [[CBMoralManager sharedManager] connectPeripheral:newPeriPheral.mPeripheral CompletionBlock:^(BOOL success, NSError *error)
                 {
                    if(success)
                    {
                        deviceStstaus = 1;
                        deviceStatusLabel.text = @"已连接";
                        
                        _bConnectSuccess = YES;
                        NSString * bleUUID = [self UUIDStringfromPeripheral:newPeriPheral];
                        [UserDefault setObject:bleUUID forKey:@"bleUUID"];
                        [UserDefault synchronize];//使用synchronize强制立即将数据写入磁盘,防止在写完NSUserDefaults后程序退出导致的数据丢失
                        
                        // 连接成功设置服务
                        NSArray *allService = [self UUIDArray:[[[CBMoralManager sharedManager] serviceUUIDDict] allKeys]];
                        
                        for(CBService *service in [[CBMoralManager sharedManager] foundServices])
                        {
                            if([allService containsObject:service.UUID] && [service.UUID.UUIDString isEqualToString:BLE_DEVICE_UUID])
                            {
                                NSInteger ServiceKeyIndex = [allService indexOfObject:service.UUID];
                                CBUUID *keyID = [allService objectAtIndex:ServiceKeyIndex];
                                
                                NSString *name = [[[[CBMoralManager sharedManager] serviceUUIDDict] valueForKey:[keyID.UUIDString lowercaseString]] objectForKey:k_SERVICE_NAME_KEY];
                                MBleService *mbleService = [[MBleService alloc]initWithName:name Service:service uuid:keyID];
                                
                                [[CBMoralManager sharedManager] setMyService:mbleService.service];
                                
                                CBService *service = [[CBMoralManager sharedManager] myService];
                                
                                [self getcharcteristicsForService:service];
                                
                            }
                            //else
                            //{
                            //    CBUUID *unknowCBUUID = service.UUID;
                            //    MBleService *mbleService = [[MBleService alloc]initWithName:@"Unknow Service" Service:service uuid:unknowCBUUID];
                            //}
                        }
 
                    }
                    else
                    {
                        if(error)
                        {
                            NSString *errorString = [error.userInfo valueForKey:NSLocalizedDescriptionKey];
                            
                            if(errorString.length)
                            {
                                [self.view makeToast:errorString];
                            }
                            else
                            {
                                [self.view makeToast:UNKNOWN_ERROR];
                            }
                        }
                    }
                    
                }];
 
            }
        }
    }
    
}
 
/*!
 *  @method UUIDStringfromPeripheral:
 *
 *  @discussion Method to get the UUID from the peripheral
 *
 */
-(NSString *)UUIDStringfromPeripheral:(CBPeripheralExt *)ble
{
    
    NSString *bleUUID2 = ble.mPeripheral.identifier.UUIDString;
    if(bleUUID2.length < 1 )
        bleUUID2 = @"Nil";
    else
        bleUUID2 = [NSString stringWithFormat:@"%@",bleUUID2];
    
    return bleUUID2;
}
 
#pragma mark - ASValueTrackingSliderDelegate
- (NSString *)slider:(ASValueTrackingSlider *)slider stringForValue:(float)value
{
    NSString * valueStr = [NSString stringWithFormat:@"%d",(int)value];
    //self._wenDuStr = valueStr;
    
    LOG_INFO(@"当前选择数值:%@℃",valueStr);
    
    //hotelSelModel.ad_speed = (int)value;
    circle3.progress = [valueStr floatValue]/100;
    
    [self setGaugeValue:slider.value animation:NO];
    
    return valueStr;
}
 
- (void)sliderWillDisplayPopUpView:(ASValueTrackingSlider *)slider{
    
}
 
- (void)sliderDidHidePopUpView:(ASValueTrackingSlider *)slider{
    
}
 
#define MAXOFFSETANGLE 152.0f
#define MAXVALUE       100.0f
 
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"辐射检测";
    [self setNavigationRight:@"icon_story.png" sel:@selector(storyAticon)];
 
    gaugeValue = 0.0f;
    gaugeAngle = -MAXOFFSETANGLE;
    maxNum = MAXVALUE;
    minNum = 0.0f;
    minAngle = -MAXOFFSETANGLE;
    maxAngle = MAXOFFSETANGLE;
    angleperValue = (maxAngle - minAngle)/(maxNum - minNum);
    // Do any additional setup after loading the view.
    
    deviceStstaus = 0;
    hexSend = YES;
    _bConnectSuccess = NO;
    
    _trackingSlider = [[ASValueTrackingSlider alloc]initWithFrame:CGRectMake(10, 40, SCREEN_WIDTH-20, 40)];
    
    _trackingSlider.delegate = self;
    _trackingSlider.dataSource = self;
    _trackingSlider.popUpViewCornerRadius = 5.0;
    [_trackingSlider setMaxFractionDigitsDisplayed:0];
    _trackingSlider.popUpViewColor = kUIColorFromRGB(0x00b744);
    _trackingSlider.font = [UIFont fontWithName:@"GillSans-Bold" size:12];
    _trackingSlider.textColor = [UIColor whiteColor];
    _trackingSlider.maximumValue = 100;
    _trackingSlider.minimumValue = 0;
    //_trackingSlider.formatStr = @"%@℃";
    //[_trackingSlider setValue: [__wenDuStr intValue]];
    [_trackingSlider showPopUpView];
    //[self.view addSubview:_trackingSlider];
    
    CGFloat unitFontSize = 14;
    CGFloat jiliangFontSize = 14;
    CGFloat numFontSize = 18;
    CGFloat tipsFontSize = 16;
    CGFloat scale = 1.0;
    CGFloat pointerOffset = 0;
    if( IsiPhone4 || IsiPhone5 )
    {
        unitFontSize = 12;
        jiliangFontSize = 12;
        numFontSize = 14;
        tipsFontSize = 13;
        scale = 0.8;
        pointerOffset = 5;
    }
    
    UIImageView * ic_head_bg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 66*scale)];
    ic_head_bg.image = [UIImage imageNamed:@"ic_head_bg"];
    [self.view addSubview:ic_head_bg];
 
    ic_anquan_status = [[UIImageView alloc] initWithFrame:CGRectMake(ic_head_bg.frame.size.width-60*scale, 3,60*scale, 60*scale)];
    ic_anquan_status.image = [UIImage imageNamed:@"ic_anquan_bk"];
    [ic_head_bg addSubview:ic_anquan_status];
 
    UIImageView * ic_line = [[UIImageView alloc] initWithFrame:CGRectMake(ic_head_bg.frame.size.width/2, 13*scale, 1, 40*scale)];
    ic_line.image = [UIImage imageNamed:@"ic_line"];
    [ic_head_bg addSubview:ic_line];
    
 
    
    GloriaLabel* _LeijiJiliangLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(66*scale, 13*scale,ic_head_bg.frame.size.width/2-66*scale, 20*scale)];
    _LeijiJiliangLabel.font = [UIFont systemFontOfSize:jiliangFontSize];
    _LeijiJiliangLabel.textAlignment = UITextAlignmentCenter;
    _LeijiJiliangLabel.textColor = kUIColorFromRGB(0xa89fa0);
    _LeijiJiliangLabel.text = @"累计计量(uSv)";
    [ic_head_bg addSubview:_LeijiJiliangLabel];
    
    _JiliangNumLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(66*scale, 33*scale,ic_head_bg.frame.size.width/2-66*scale-30, 20*scale)];
    _JiliangNumLabel.font = [UIFont boldSystemFontOfSize:numFontSize];
    _JiliangNumLabel.textAlignment = UITextAlignmentRight;
    _JiliangNumLabel.textColor = kUIColorFromRGB(0x07cb5a);
    _JiliangNumLabel.text = @"0.0";
    [ic_head_bg addSubview:_JiliangNumLabel];
    
    //GloriaLabel* _JiliangUnitLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(66*scale+_JiliangNumLabel.frame.size.width, 33*scale,30*scale, 20*scale)];
    //_JiliangUnitLabel.font = [UIFont systemFontOfSize:unitFontSize];
    //_JiliangUnitLabel.textAlignment = UITextAlignmentLeft;
   // _JiliangUnitLabel.textColor = kUIColorFromRGB(0xa89fa0);
   // _JiliangUnitLabel.text = @"(月)";
   // [ic_head_bg addSubview:_JiliangUnitLabel];
    
    
    GloriaLabel* _BiaozhunJiliangLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(ic_head_bg.frame.size.width/2, 13*scale,ic_head_bg.frame.size.width/2-60*scale, 20*scale)];
    _BiaozhunJiliangLabel.font = [UIFont systemFontOfSize:jiliangFontSize];
    _BiaozhunJiliangLabel.textAlignment = UITextAlignmentCenter;
    _BiaozhunJiliangLabel.textColor = kUIColorFromRGB(0xa89fa0);
    _BiaozhunJiliangLabel.text = @"实时计量(uSv/h)";
    [ic_head_bg addSubview:_BiaozhunJiliangLabel];
    
    _BiaozhunJiliangNumLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(ic_head_bg.frame.size.width/2, 33*scale,ic_head_bg.frame.size.width/2-60*scale-30, 20*scale)];
    _BiaozhunJiliangNumLabel.font = [UIFont boldSystemFontOfSize:numFontSize];
    _BiaozhunJiliangNumLabel.textAlignment = UITextAlignmentRight;
    _BiaozhunJiliangNumLabel.textColor = kUIColorFromRGB(0xff9c66);
    _BiaozhunJiliangNumLabel.text = @"0.0";
    [ic_head_bg addSubview:_BiaozhunJiliangNumLabel];
    
    
    UIImageView * icon_anquan = [[UIImageView alloc] initWithFrame:CGRectMake(19*scale, 10*scale, 22*scale, 22*scale)];
    icon_anquan.image = [UIImage imageNamed:@"icon_head_offline"];
    [ic_anquan_status addSubview:icon_anquan];
    
    
    _AnquanStatustLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(0, 35*scale,60*scale, 20*scale)];
    _AnquanStatustLabel.font = [UIFont systemFontOfSize:unitFontSize];
    _AnquanStatustLabel.textAlignment = UITextAlignmentCenter;
    _AnquanStatustLabel.textColor = kUIColorFromRGB(0x07cb5a);
    _AnquanStatustLabel.text = @"安全";
    [ic_anquan_status addSubview:_AnquanStatustLabel];
    
    
    ic_zhishu_bk = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-245*scale)/2, (66+20+292+20)*scale, 245*scale, 48*scale)];
    ic_zhishu_bk.image = [UIImage imageNamed:@"ic_zhishu_bk"];
    [self.view addSubview:ic_zhishu_bk];
    
    
    _currentShuziTipsLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(0, 10*scale,245*scale, 20*scale)];
    _currentShuziTipsLabel.font = [UIFont boldSystemFontOfSize:tipsFontSize];
    _currentShuziTipsLabel.textAlignment = UITextAlignmentCenter;
    _currentShuziTipsLabel.textColor = [UIColor whiteColor];
    _currentShuziTipsLabel.text = @"未开始检测";
    [ic_zhishu_bk addSubview:_currentShuziTipsLabel];
    
    UIImageView * ic_bottom_bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64-88*scale-44, SCREEN_WIDTH, 88*scale)];
    ic_bottom_bg.image = [UIImage imageNamed:@"ic_radia_bottom_bg"];
    [self.view addSubview:ic_bottom_bg];
    
    _currentTipsLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 88*scale)];
    _currentTipsLabel.font = [UIFont boldSystemFontOfSize:tipsFontSize];
    _currentTipsLabel.textAlignment = UITextAlignmentCenter;
    _currentTipsLabel.textColor = RgbColor(64, 159, 252);
    _currentTipsLabel.numberOfLines = 2;
    _currentTipsLabel.text = @"未开始检测";
    [ic_bottom_bg addSubview:_currentTipsLabel];
    
    ic_weixin_tips = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-34*scale)/2, -17*scale, 34*scale, 34*scale)];
    ic_weixin_tips.image = [UIImage imageNamed:@"ic_weixin_tips"];
    [ic_bottom_bg addSubview:ic_weixin_tips];
    
    
    UIButton* ic_zhuanpan_bkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    ic_zhuanpan_bkBtn.frame = CGRectMake((SCREEN_WIDTH-306*scale)/2, 66*scale+20*scale, 306*scale, 292*scale);
    [ic_zhuanpan_bkBtn setBackgroundImage:[UIImage imageNamed:@"ic_zhuanpan_bk" ] forState:UIControlStateNormal];
    [ic_zhuanpan_bkBtn addTarget:self action:@selector(connectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ic_zhuanpan_bkBtn];
    
    //自定义起始角度、自定义小圆点、动画从上次数值开始
    circle3 = [[ZZCircleProgress alloc] initWithFrame:CGRectMake((ic_zhuanpan_bkBtn.frame.size.width-180*scale)/2-2*scale, 60*scale, 182*scale, 182*scale) pathBackColor:RgbColor(184,237, 254) pathFillColor:RgbColor(85,197, 252)  startAngle:-235 strokeWidth:24*scale];
    circle3.reduceValue = 72;
    circle3.increaseFromLast = YES;
    circle3.pointImage = [UIImage imageNamed:@"test_point"];
    circle3.progress = ((float)850/FUSHE_MAX_VALUE);
    //circle3.progress = 0;
    circle3.showProgressText = NO;
    circle3.userInteractionEnabled = NO;
    [ic_zhuanpan_bkBtn addSubview:circle3];
    [_trackingSlider setValue:circle3.progress*100];
    
    //deviceStatusLabel
    deviceStatusLabel = [[GloriaLabel alloc] initWithFrame:CGRectMake((ic_zhuanpan_bkBtn.frame.size.width-60*scale)/2, 180*scale, 60*scale, 20*scale)];
    deviceStatusLabel.font = [UIFont boldSystemFontOfSize:unitFontSize];
    deviceStatusLabel.textAlignment = UITextAlignmentCenter;
    deviceStatusLabel.textColor = RgbColor(64, 159, 252);
    deviceStatusLabel.text = @"未连接";
    [ic_zhuanpan_bkBtn addSubview:deviceStatusLabel];
    
    ic_pointer = [[UIImageView alloc] initWithFrame:CGRectMake((ic_zhuanpan_bkBtn.frame.size.width-50*scale)/2, 91*scale+pointerOffset, 50*scale, 111*scale)];
    ic_pointer.image = [UIImage imageNamed:@"ic_pointer"];
    
    //添加指针
    ic_pointer.layer.anchorPoint = CGPointMake(0.5, 0.78);
    //ic_pointer.center = CGPointMake((ic_zhuanpan_bk.frame.size.width-50)/2, 64);
    //ic_pointer.transform = CGAffineTransformMakeScale(1, 1);
    //设置指针到0位置
    ic_pointer.layer.transform = CATransform3DMakeRotation([self transToRadian:-MAXOFFSETANGLE], 0, 0, 1);
    [ic_zhuanpan_bkBtn addSubview:ic_pointer];
 
    //[self setGaugeValue:((float)850/FUSHE_MAX_VALUE)*100 animation:NO];
    //适配ios7
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
    {
        self.navigationController.navigationBar.translucent = NO;
    }
    _locService = [[BMKLocationService alloc]init];
    
    _locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    //[self startLocation];
    
    dataModelArr = [[NSMutableArray alloc] init];
    
    myTimeInterval = [UserDefault stringForKey:@"refresh_frequency"];
    is_open_upload = [UserDefault stringForKey:@"is_open_upload"];
    
    [self offLineSet];
    //myTimer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];
    //每1秒运行一次function方法。
    
}
 
-(void)offLineSet
{
    _AnquanStatustLabel.text = @"离线";
    _AnquanStatustLabel.textColor = kUIColorFromRGB(0x848787);
    deviceStatusLabel.text = @"未连接";
    deviceStatusLabel.textColor = kUIColorFromRGB(0x848787);
    icon_anquan.image = [UIImage imageNamed:@"icon_head_offline"];
    ic_anquan_status.image = [UIImage imageNamed:@"bg_corner_gray"];
    ic_weixin_tips.image = [UIImage imageNamed:@"icon_offline"];
    ic_zhishu_bk.image = [UIImage imageNamed:@"bt_offline"];
    _currentTipsLabel.textColor = kUIColorFromRGB(0x848787);
}
 
-(void)connectAction
{
    SearchDevicePage* page = [[SearchDevicePage alloc] initIsFirstPage:NO];
 
    BaseNaviController *baseNav = [[BaseNaviController alloc] initWithRootViewController:page];
    [self presentViewController:baseNav animated:YES completion:nil];
}
 
-(void)storyAticon
{
    HistoryRecordPage* page = [[HistoryRecordPage alloc] initIsFirstPage:NO];
    
    BaseNaviController *baseNav = [[BaseNaviController alloc] initWithRootViewController:page];
    [self presentViewController:baseNav animated:YES completion:nil];
}
 
 
/*
 * parseToAngle 根据数据计算需要转动的角度
 * @val CGFloat 要移动到的数值
 */
-(CGFloat) parseToAngle:(CGFloat) val
{
    //异常的数据
    if(val<minNum)
    {
        return minNum;
    }
    else if(val>maxNum)
    {
        return maxNum;
    }
    CGFloat temp =(val-gaugeValue)*angleperValue;
    return temp;
}
 
 
/*
 * setGaugeValue 移动到某个数值
 * @value CGFloat 移动到的数值
 * @isAnim BOOL   是否执行动画
 */
-(void)setGaugeValue:(CGFloat)value animation:(BOOL)isAnim
{
    CGFloat tempAngle = [self parseToAngle:value];
    gaugeValue = value;
    //设置转动时间和转动动画
    if(isAnim){
        [self pointToAngle:tempAngle Duration:0.6f];
    }else
    {
        [self pointToAngle:tempAngle Duration:0.0f];
    }
}
 
/*
 * pointToAngle 按角度旋转
 * @angel CGFloat 角度
 * @duration CGFloat 动画执行时间
 */
- (void) pointToAngle:(CGFloat) angle Duration:(CGFloat) duration
{
    CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"transform"];
    NSMutableArray *values=[NSMutableArray array];
    anim.duration = duration;
    anim.autoreverses = NO;
    anim.fillMode = kCAFillModeForwards;
    anim.removedOnCompletion= NO;
    
    CGFloat distance = angle/10;
    //设置转动路径,不能直接用 CABaseAnimation 的toValue,那样是按最短路径的,转动超过180度时无法控制方向
    int i = 1;
    for(;i<=10;i++)
    {
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*i)], 0, 0, 1)]];
    }
    //添加缓动效果
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i))], 0, 0, 1)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-2))], 0, 0, 1)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DRotate(CATransform3DIdentity, [self transToRadian:(gaugeAngle+distance*(i-1))], 0, 0, 1)]];
    
    anim.values=values; ;
    [ic_pointer.layer addAnimation:anim forKey:@"cubeIn"];
    
    gaugeAngle = gaugeAngle+angle;
    
}
 
/*
 * parseToX 角度转弧度
 * @angel CGFloat 角度
 */
-(CGFloat)transToRadian:(CGFloat)angel
{
    return angel*M_PI/180;
}
 
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
 
-(void)data_upload
{
    //[UserDefault stringForKey:@"user_id"]
    NSString *path = [[NSString alloc] initWithFormat:DATA_UPLOAD];
    
    UploadModel *model = [[UploadModel alloc] init];
    
    //['refresh_frequency', 'video', 'is_open_upload']
    //[param setValue:[UserDefault stringForKey:@"user_id"] forKey:@"user_id"];
    
    model.lat = [NSString stringWithFormat:@"%lf",latitude];
    model.lon = [NSString stringWithFormat:@"%lf",longitude];
    model.userid = [UserDefault stringForKey:@"user_id"];
    model.address = address;
    model.modelArray = [[NSMutableArray alloc] init];
    [model.modelArray addObjectsFromArray:dataModelArr];
    
    MPWeakSelf(self);
    [NetworkSingleton networkingGetMethod:model.toDic urlName:path success:^(id responseBody)
     {
         MPStrongSelf(self);
         BaseResModel * resModel = [Global toBaseModel:responseBody];
         
         if(resModel.code == 0)
         {
             [dataModelArr removeAllObjects];
             
             //[UserDefault setObject:self.is_open_upload forKey:@"is_open_upload"];
             [UserDefault synchronize];
             
             //[self.tableView reloadData];
             [Global alertMessageEx:resModel.desc title:@"提示信息" okTtitle:nil cancelTitle:@"OK" delegate:self];
         }
         else
         {
             [Global alertMessageEx:resModel.desc title:@"提示信息" okTtitle:nil cancelTitle:@"OK" delegate:self];
         }
     }
                                  failure:^(NSString *error)
     {
         
         [Global alertMessageEx:error title:@"获取失败" okTtitle:nil cancelTitle:@"OK" delegate:self];
     }];
}
 
//普通态
-(void)startLocation
{
    NSLog(@"进入普通定位态");
    [_locService startUserLocationService];
    //_mapView.showsUserLocation = NO;//先关闭显示的定位图层
    //_mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    //_mapView.showsUserLocation = YES;//显示定位图层
}
 
//停止定位
-(void)stopLocation:(id)sender
{
    [_locService stopUserLocationService];
    //_mapView.showsUserLocation =  YES;//显示定位图层
}
 
/**
 *用户方向更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //[_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}
 
/**
 *用户位置更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    
    // 3.CLGeocoder反向通过经纬度,获得城市名
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0)
        {
            CLPlacemark *placemark = [array objectAtIndex:0];
            NSDictionary *addressDictionary = placemark.addressDictionary;
            
            address = [NSString stringWithFormat:@"%@", [addressDictionary valueForKey:@"FormattedAddressLines"]];
            //address = [NSString stringWithCString:[address cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
        }
    }];
    
    //[_mapView updateLocationData:userLocation];
    
    //_mapView.centerCoordinate = userLocation.location.coordinate; //更新当前位置到地图中间
}
 
 
/**
 *在地图View将要启动定位时,会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}
 
/**
 *在地图View停止定位后,会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}
 
/**
 *定位失败后,会调用此函数
 *@param mapView 地图View
 *@param error 错误号,参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}
 
- (void)dealloc {
   // if (_mapView) {
    //    _mapView = nil;
   // }
}
 
/*
#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