BlueToolManage.m 2.91 KB
//
//  BuleToolManage.m
//  metroApp
//
//  Created by 赵世强 on 2018/3/26.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "BlueToolManage.h"


@implementation BlueToolManage

{
  CLLocationManager *_locationManager;
  
  CLBeaconRegion *_region;
  
  NSArray *_detectedBeacons;
  
  CLBeacon *beacon_current;
  
  NSTimer *timer;
  
}

RCT_EXPORT_MODULE(BlueToolManage);
- (instancetype)init
{
  if(self = [super init]){
    [self initLocationManager];
    [self initBeaconRegion];
    [self initDetectedBeaconsList];
    [self startBeaconRanging];
    
  }
  return self;
}

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

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

RCT_EXPORT_METHOD(stopTimer)
{
  [timer invalidate];
  timer = nil;
}

- (void)postCurrentLocation{
  
  [self sendEventWithName:@"BlueToolData" body:@{@"deviceCode": [NSString stringWithFormat:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0|%@|%@",beacon_current.major,beacon_current.minor],@"rss": [NSString stringWithFormat:@"%ld",(long)beacon_current.rssi]}];
  
}

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

- (void) initBeaconRegion{
  if (_region)
    return;
  
  NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:@"E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"];
  _region = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID identifier:@"cell"];
  _region.notifyEntryStateOnDisplay = YES;
}

- (void) initDetectedBeaconsList{
  if (!_detectedBeacons) {
    _detectedBeacons = [[NSArray 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:_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 {
    _detectedBeacons = beacons;
    NSInteger currentrssi = -9999;
    for (CLBeacon *beacon in _detectedBeacons) {
      if (beacon.rssi > currentrssi) {
        currentrssi = beacon.rssi;
        beacon_current = beacon;
      }
    }

  }
}

- (void)checkLocationAccessForRanging {
  if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [_locationManager requestWhenInUseAuthorization];
  }
}

@end