BlueToolManage.m 11.5 KB
//
//  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 <ifaddrs.h>
#import <arpa/inet.h>

@implementation BlueToolManage

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

RCT_EXPORT_MODULE(BlueToolManage);
- (instancetype)init
{
  if(self = [super init]){
    manage =[[CBCentralManager alloc]initWithDelegate:self queue:nil];
    [self initLocationManager];
    [self initBeaconRegion];
    [self initDetectedBeaconsList];
    [self startBeaconRanging];
    
  }
  return self;
}

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

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

RCT_EXPORT_METHOD(stopTimer)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    [timer invalidate];
    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;
    put.objectKey = object;
    
    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:object];
        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;
  
  if ([wifiName isEqualToString:@"花生地铁WiFi"]) {
    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]];
        }
      }
    }
  }
  
  
  [self sendEventWithName:@"BlueToolData" body:@{@"deviceCode": beacon_current?[NSString stringWithFormat:@"%@|%@|%@",[beacon_current.proximityUUID UUIDString],beacon_current.major?beacon_current.major:@"",beacon_current.minor?beacon_current.minor:@""]:@"",@"rss":beacon_current.rssi? [NSString stringWithFormat:@"%ld",(long)beacon_current.rssi]:@"",@"wRSS":@"",@"wBSSID":BSSID?BSSID:@"",@"wIP":![[self getIPAddress] isEqualToString:@"error"]?[self getIPAddress]:@""}];
  
  [_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;
  
  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 {

    NSInteger currentrssi = -9999;
    for (CLBeacon *beacon in beacons) {
      [_detectedBeacons addObject:beacon];

    }
    
  }
}

- (void)checkLocationAccessForRanging {
  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;
}

@end