BlueToolManage.m 17.4 KB
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
//
//  BuleToolManage.m
//  metroApp
//
//  Created by 赵世强 on 2018/3/26.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "BlueToolManage.h"
#import "AppDelegate.h"
#import <AliyunOSSiOS/OSSService.h>
#import "ZLPhotoConfiguration.h"
#import "XNCameraManager.h"
#import "RequestData.h"
#import "BlueToolManage.h"

#import <ifaddrs.h>
#import <arpa/inet.h>

//判断系统版本用
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

@implementation BlueToolManage

{
  CLLocationManager *_locationManager;
  
  CLBeaconRegion *_region;
  
  NSMutableArray *_detectedBeacons;
  
  CLBeacon *beacon_current;
  
  NSTimer *timer;
  
  //定义变量
  CBCentralManager *manage;
  
  BOOL blueOpen;
  
  AMapLocationManager *locationManager;
  
  AMapGeoFenceManager *geoFenceManager;
  
}

+ (id)allocWithZone:(NSZone *)zone {
  
  static BlueToolManage *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [super allocWithZone:zone];
    
  });

  return sharedInstance;
}

RCT_EXPORT_MODULE(BlueToolManage);
- (instancetype)init
{
  self = [super init];
  manage =[[CBCentralManager alloc]initWithDelegate:self queue:nil];
  [self initLocationManager];
  [self initBeaconRegion];
  [self initDetectedBeaconsList];
  [self startBeaconRanging];
  
  locationManager = [[AMapLocationManager alloc] init];
  locationManager.delegate = self;
  locationManager.distanceFilter = 50;
  [locationManager setLocatingWithReGeocode:YES];
  [locationManager startUpdatingLocation];
  
  geoFenceManager = [[AMapGeoFenceManager alloc] init];
  geoFenceManager.delegate = self;
  geoFenceManager.activeAction = AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside | AMapGeoFenceActiveActionStayed; //设置希望侦测的围栏触发行为,默认是侦测用户进入围栏的行为,即AMapGeoFenceActiveActionInside,这边设置为进入,离开,停留(在围栏内10分钟以上),都触发回调
  //    geoFenceManager.allowsBackgroundLocationUpdates = YES;
  
  return self;
}

- (NSArray<NSString *> *)supportedEvents {
  return @[@"BlueToolData",@"locationData"]; //这里返回的将是你要发送的消息名的数组。
}

RCT_EXPORT_METHOD(startTimer:(NSString *)timeInterval)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    self->timer = [NSTimer scheduledTimerWithTimeInterval:[timeInterval intValue] target:self selector:@selector(postCurrentLocation) userInfo:nil repeats:YES];
    [self->timer fire];
  });
  
}

RCT_EXPORT_METHOD(stopTimer)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    [self->timer invalidate];
    self->timer = nil;
  });
}

RCT_EXPORT_METHOD(getPhoneNumber
                  :(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  if ([AppDelegate sharedInstance].str_phone) {
    resolve([AppDelegate sharedInstance].str_phone?[AppDelegate sharedInstance].str_phone:@"");
  }
  
}

RCT_EXPORT_METHOD(getCurrentStatus
                  :(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  resolve(@"0");
}

RCT_EXPORT_METHOD(getAppVersion
                  :(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  NSString * localVersionShort = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
  
  resolve(localVersionShort);
}

#pragma mark - 拍摄文件上传(包含图片/视频)
RCT_EXPORT_METHOD(openCameraWithpassportId:(NSString *)passportId resolve:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  
  dispatch_async(dispatch_get_main_queue(), ^{
    
    [[XNCameraManager sharedInstance] showCameraWithController:[self topViewController] passportId:passportId];
    [XNCameraManager sharedInstance].finshBlock = ^(NSDictionary *dict){
      if (dict) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:nil];
        
        NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                     encoding:NSUTF8StringEncoding];
        
        resolve([NSString stringWithFormat:@"%@",jsonString]);
      }
      
    };
    
  });
  
}

#pragma mark - 相册文件上传(包含图片/视频)
RCT_EXPORT_METHOD(simpleUpload:(NSString *)keyId secretId:(NSString *)secretId token:(NSString *)token endpoint:(NSString *)endpoint mBucket:(NSString *)mBucket object:(NSString *)object filePath:(NSString *)filePath resolve:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  dispatch_async(dispatch_get_main_queue(), ^{
  
    ZLProgressHUD *hud = [[ZLProgressHUD alloc] init];
    [hud show];
    
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:keyId secretKeyId:secretId securityToken:token];
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // 必填字段
    put.bucketName = mBucket;
    NSString *string = [object mutableCopy];
    
    if ([[string substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"/"]) {
      string =  [object substringWithRange:NSMakeRange(1, object.length-1)];
      
    }
    put.objectKey = string;
    
    put.uploadingData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
    
    OSSTask * putTask = [client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
      if (!task.error) {
        NSLog(@"upload object success! 上传文件成功");
        NSString * constrainURL = nil;
        OSSTask *result = [client presignPublicURLWithBucketName:mBucket
                                                   withObjectKey:string];
        if (!result.error) {
          [hud hide];
          constrainURL = result.result;
          resolve([NSString stringWithFormat:@"%@",constrainURL]);
          NSLog(@"error: %@", constrainURL);
        } else {
          [hud hide];
          NSLog(@"error: %@", result.error);
        }
        
      } else {
        [hud hide];
        NSLog(@"upload object failed, error: %@" , task.error);
      }
      return nil;
    }];
    
  });
  
}

- (void)postCurrentLocation{
  
//  NSInteger currentrssi = -9999;
  
//  if (_detectedBeacons.count>20) {
//    [_detectedBeacons removeObjectsInRange:NSMakeRange(0, _detectedBeacons.count-20)];
//  }
  
//  for (CLBeacon *beacon in _detectedBeacons) {
//    if (beacon.rssi <0) {
//      if (beacon.rssi > currentrssi) {
//        currentrssi = beacon.rssi;
//        beacon_current = beacon;
//      }
//    }
//  }
  
  if (!blueOpen) {
    beacon_current = nil;
  }
  
//  NSLog(@"beacons found nearby.---%@ ----%@ -----%@",[beacon_current.proximityUUID UUIDString],beacon_current.major,beacon_current.minor);
  
  NSDictionary *dict_wifi = [self SSIDInfo];
  NSArray *strarray = [[dict_wifi objectForKey:@"BSSID"] componentsSeparatedByString:@":"];
  NSString *wifiName = [dict_wifi objectForKey:@"SSID"];
  NSString *BSSID;
  
  BOOL isWiFi = NO;
  //花生地铁WiFi
  if ([wifiName isEqualToString:@"花生地铁WiFi"]) {
    isWiFi = YES;
    for (int i = 0; i<strarray.count; i++) {
      NSString *bssid = strarray[i];
      if (i == 0) {
        if (bssid.length==1) {
          BSSID = [@"0" stringByAppendingString:bssid];
        }else{
          BSSID = bssid ;
        }
      }else{
        if (bssid.length==1) {
          BSSID = [BSSID stringByAppendingString:[NSString stringWithFormat:@":0%@",bssid]];
        }else{
          BSSID = [BSSID stringByAppendingString:[NSString stringWithFormat:@":%@",bssid]];
        }
      }
    }
  }
  
  NSMutableArray *arr_requestData = [[NSMutableArray alloc]init];
  
  for (CLBeacon *beacon in _detectedBeacons) {
    RequestData *data = [[RequestData alloc]init];
    data.deviceCode = [NSString stringWithFormat:@"%@|%@|%@",[beacon.proximityUUID UUIDString],beacon.major?beacon.major:@"",beacon.minor?beacon.minor:@""];
    data.RSS = [NSString stringWithFormat:@"%ld",(long)beacon.rssi];
    data.deviceType = 2;
    data.deviceMac = @"";

    [arr_requestData addObject:@{@"deviceCode":[NSString stringWithFormat:@"%@|%@|%@",[beacon.proximityUUID UUIDString],beacon.major?beacon.major:@"",beacon.minor?beacon.minor:@""],@"RSS":[NSString stringWithFormat:@"%ld",(long)beacon.rssi],@"deviceType":@"2",@"deviceMac":@""}];
  };
  
  
  if (isWiFi) {
    [self sendEventWithName:@"BlueToolData" body:@{@"requestData":arr_requestData,@"wifiData":@{@"wIP":![[self getIPAddress] isEqualToString:@"error"]?[self getIPAddress]:@"",@"wBSSID":BSSID?BSSID:@"",@"wRSS":@""}}];
  }else{
    [self sendEventWithName:@"BlueToolData" body:@{@"requestData":arr_requestData}];
  }
  
  [_detectedBeacons removeAllObjects];
}

#pragma mark Init Beacons
- (void) initLocationManager{
  if (!_locationManager) {
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    [self checkLocationAccessForRanging];
  }
}

- (void) initBeaconRegion{
  if (_region)
    return;
  
//  NSUUID *proximityUUID1 = [[NSUUID alloc] initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"];
//  _region1 = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID1 identifier:@"cell1"];
//  _region1.notifyEntryStateOnDisplay = YES;
//  FDA50693-A4E2-4FB1-AFCF-C6EB07647825
  NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:@"FDA50693-A4E2-4FB1-AFCF-C6EB07647825"];
  _region = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID identifier:@"cell"];
  _region.notifyEntryStateOnDisplay = YES;
  
  
}

- (void) initDetectedBeaconsList{
  if (!_detectedBeacons) {
    _detectedBeacons = [[NSMutableArray alloc] init];
  }
}

#pragma mark Beacons Ranging
- (void) startBeaconRanging{
  if (!_locationManager || !_region) {
    return;
  }
  if (_locationManager.rangedRegions.count > 0) {
    NSLog(@"Didn't turn on ranging: Ranging already on.");
    return;
  }
  
//  [_locationManager startRangingBeaconsInRegion:_region1];
  [_locationManager startRangingBeaconsInRegion:_region];
  
}


//Location manager delegate method
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
  if (beacons.count == 0) {
    NSLog(@"No beacons found nearby.");
    beacon_current = nil;
  } else {

    for (CLBeacon *beacon in beacons) {
      [_detectedBeacons addObject:beacon];

    }
    
  }
}

- (void)checkLocationAccessForRanging {
  if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"13.0")){
      if (@available(iOS 13.0, *)) {
          // 如果是>=iOS13 未开启地理位置权限 需要提示一下
          if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ||
              [CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted ||
              [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
              _locationManager = [[CLLocationManager alloc] init];
              [_locationManager requestWhenInUseAuthorization];
              return;
          }
      }
  }
  if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"14.0")){
      if (@available(iOS 14.0, *)) {
          // 如果没有开启精确定位,临时授权
          BOOL isFullAccuracy = _locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy;
          if (!isFullAccuracy) {
              // 向用户申请临时开启一次精确位置权限
              [_locationManager requestTemporaryFullAccuracyAuthorizationWithPurposeKey:@"ExampleUsageDescription"];
          }
          return;
      }
  }
  if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [_locationManager requestAlwaysAuthorization];
  }
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
  switch (central.state) {
    case CBManagerStateUnknown:
      NSLog(@"CBCentralManagerStateUnknown");
      break;
    case CBManagerStateResetting:
      NSLog(@"CBCentralManagerStateResetting");
      break;
    case CBManagerStateUnsupported:
      NSLog(@"CBCentralManagerStateUnsupported");//不支持蓝牙
      break;
    case CBManagerStateUnauthorized:
      NSLog(@"CBCentralManagerStateUnauthorized");
      break;
    case CBManagerStatePoweredOff:
    {
      NSLog(@"CBCentralManagerStatePoweredOff");//蓝牙未开启
      
      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"未开启蓝牙" message:@"请关闭app,并在设置->打开蓝牙服务" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
      [alert show];
      
      blueOpen = NO;
    }
      break;
    case CBManagerStatePoweredOn:
    {
      blueOpen = YES;
      NSLog(@"CBCentralManagerStatePoweredOn");//蓝牙已开启
      
    }
      break;
    default:
      break;
  }
}

- (UIViewController *)topViewController {
  UIViewController *resultVC;
  resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
  while (resultVC.presentedViewController) {
    resultVC = [self _topViewController:resultVC.presentedViewController];
  }
  return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
  if ([vc isKindOfClass:[UINavigationController class]]) {
    return [self _topViewController:[(UINavigationController *)vc topViewController]];
  } else if ([vc isKindOfClass:[UITabBarController class]]) {
    return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
  } else {
    return vc;
  }
  return nil;
}

- (NSDictionary *)SSIDInfo {


  
  NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
  NSDictionary *info = nil;
  for (NSString *ifnam in ifs) {
    info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
    if (info && [info count]) {
      break;
    }
  }
  return info;
  
}

- (NSString *)getIPAddress {
  NSString *address = @"error";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;
  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&interfaces);
  if (success == 0) {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL) {
      if(temp_addr->ifa_addr->sa_family == AF_INET) {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
          // Get NSString from C String
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
        }
      }
      temp_addr = temp_addr->ifa_next;
    }
  }
  // Free memory
  freeifaddrs(interfaces);
  return address;
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
  NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
  if (reGeocode)
  {
    NSLog(@"reGeocode:%@", reGeocode);
  }
  
//  先清除
  [geoFenceManager removeAllGeoFenceRegions];
  CLLocationCoordinate2D coordinate = location.coordinate; //当前所在位置
  [geoFenceManager addAroundPOIRegionForMonitoringWithLocationPoint:coordinate aroundRadius:150 keyword:@"地铁站" POIType:@"150500" size:0 customID:@"poi_1"];
}

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions customID:(NSString *)customID error:(NSError *)error {
  if (error) {
    NSLog(@"创建失败 %@",error);
  } else {
    NSLog(@"创建成功");
  }
}

- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region customID:(NSString *)customID error:(NSError *)error {
  if (error) {
    NSLog(@"status changed error %@",error);
  }else{
    NSLog(@"status changed success %@",[region description]);
    AMapGeoFencePOIRegion *poi = region;
    switch (region.fenceStatus) {
      case AMapGeoFenceRegionStatusInside:
        //在氛围内
      {
        [self sendEventWithName:@"locationData" body:@{@"requestData":poi.POIItem.name}];
        
      }
        break;
      case AMapGeoFenceRegionStatusOutside:
        //范围外
      {
//        [self sendEventWithName:@"locationData" body:@{@"requestData":poi.POIItem.name}];
      }
        break;
        
      case AMapGeoFenceRegionStatusStayed:
        //停留
      {
        [self sendEventWithName:@"locationData" body:@{@"requestData":poi.POIItem.name}];
      }
        
        break;
        
      default:
        break;
    }
  }
}

- (void)amapLocationManager:(AMapGeoFenceManager *)manager doRequireTemporaryFullAccuracyAuth:(CLLocationManager *)locationManager completion:(void (^)(NSError *))completion {
  
}


@end