//
//  BTDiscoverViewController.m
//  AT188N_DEMO_1703
//
//  Created by 류은주 on 2017. 3. 2..
//  Copyright © 2017년 ATID. All rights reserved.
//

#import "BTDiscoverViewController.h"
#import "NewDeviceTableViewCell.h"
#import "EAScanDeviceItem.h"
#import "SWRevealViewController.h"
#import "PairedDeviceTableViewCell.h"

@interface BTDiscoverViewController ()
{
    NSString * lastDeviceAddress;
    NSString * lastDeviceName;
    UIImage *connectdeviceimg;
    UIImage *connectstate;
    
    BOOL bleready;
    BOOL wrongdeviceflag;
    
    //    NSThread *batterystateThread;
    
    BOOL isDeviceOn;
    NSString * connectdevicename;
    BOOL actionFlag;
    NSMutableArray *aryDevices;
}
@property (weak, nonatomic) IBOutlet UIButton *searchstopBtn;
@property (weak, nonatomic) IBOutlet UITableView *newdevicetableview;
@property (weak, nonatomic) IBOutlet UITableView *paireddevicetableview;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activeindicator;
@property (weak, nonatomic) IBOutlet UIImageView *lastDeviceImg;
@property (weak, nonatomic) IBOutlet UILabel *lastDeviceNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *devicestateImg;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;

@end

@implementation BTDiscoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    bleready = 0;
    wrongdeviceflag = 0;
    
    //    _deviceInfo = [[DeviceSelectInfoDB alloc] init];
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        dispatch_async(dispatch_get_main_queue(), ^{
            appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        });
   
        mPeripherals = [NSMutableArray new];
        mDevice = nil;
        
        mQueue = dispatch_queue_create("com.atid.bluetooth", NULL);
        
        appDelegate.mCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:mQueue];
        
    });
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(BluetoothDisconnected:) name:@"BluetoothDisconnected" object:nil];
    [center addObserver:self selector:@selector(wrongdeviceconnected:) name:@"wrongdeviceconnected" object:nil];
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    [appDelegate.mReader setDelegate:self];
    appDelegate.mCentralManager.delegate = self;
    
    //    appDelegate.connectdeviceadd  = [_deviceInfo getBTInfoAddress];
    //    appDelegate.connectdevicename = [_deviceInfo getBTInfoname];
    _deviceInfo = [[DeviceSelectInfoDB alloc] init];
    aryDevices = [[NSMutableArray alloc] init];
    aryDevices = [_deviceInfo getArrayData];
    actionFlag = 0;
    //[self getlastdeviceinfo];
    connectdeviceimg = [UIImage imageNamed:@"ic_product_at288.png"];
    [self.paireddevicetableview reloadData];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // Stop Scan Peripherals Device
    [self stopScanDevice];
    
    [mPeripherals removeAllObjects];
    [self.newdevicetableview reloadData];
    [self.paireddevicetableview reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wrongdeviceconnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BluetoothDisconnected" object:nil];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}
- (void)getconnectedinfo:(NSString *)device {
    
    lastDeviceName = appDelegate.latestdevicename;
    NSString *deviceName;
    
    deviceName = appDelegate.connectdevicename;
    
    if (device != nil) {
       /*
        NSRange range1 = [deviceName rangeOfString:@"AT188"];
        NSRange range2 = [deviceName rangeOfString:@"AT288"];
        NSRange range3 = [deviceName rangeOfString:@"AT388"];
        NSRange range4 = [deviceName rangeOfString:@"ATS100"];
        
        
      if (range1.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at188.png"];
        }else if(range2.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at288.png"];
        }else if(range3.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_at388.png"];
        }else if(range4.location != NSNotFound){
            connectdeviceimg = [UIImage imageNamed:@"ic_product_atsl.png"];
        }else {
            connectdeviceimg = [UIImage imageNamed:@"ic_unknown.png"];
        }*/
        
        
        NSLog(@"BTDiscoverViewController appDelegate.mPeripheral.state  [%d]",appDelegate.mPeripheral.state);
        if([device isEqualToString:deviceName]){
            if(appDelegate.mPeripheral.state == CBPeripheralStateConnected){
                connectstate = [UIImage imageNamed:@"btn_more_blue_normal.png"];
            }else {
                connectstate = [UIImage imageNamed:@"btn_more_red_normal.png"];
            }
        }else {
            connectstate = [UIImage imageNamed:@"btn_more_red_normal.png"];
        }
        
    }else {
        connectdeviceimg = [UIImage imageNamed:@"ic_unknown.png"];
        connectstate = [UIImage imageNamed:@"ic_unknown.png"];
    }
    
//    [self.lastDeviceImg setImage:connectdeviceimg];
//    [self.devicestateImg setImage:connectstate];
//    self.lastDeviceNameLabel.text = deviceName;
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.paireddevicetableview reloadData];
//    });
    
}
- (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.
 }
 */
- (IBAction)searchstopBtntapped:(id)sender {
    
    if(bleready == 1){
        [self stopScanDevice];
//        [self indicatorEnable: 0];
        //        self.activeindicator.hidden = YES;
        //        [self.activeindicator stopAnimating];
        [self.startBtn setTitle:@"Search" forState:UIControlStateNormal];
    } else {
        [self clearScanDevice];
        [self startScanDevice];
        [self indicatorEnable: 1];
        //        self.activeindicator.hidden = NO;
        //        [self.activeindicator startAnimating];
        [self.startBtn setTitle:@"Stop" forState:UIControlStateNormal];
    }
}
- (void) devicesearchstart {
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        mDevice = nil;
        
        [appDelegate.mReader disconnect];
        
        appDelegate.mReader = nil;
        
    });
}
- (void) devicesearchstop {
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (tableView == _newdevicetableview){
        return mPeripherals.count;
    } else {
        return aryDevices.count;
    }
}

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _newdevicetableview){
        NewDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewDeviceCell" forIndexPath:indexPath];
        
        EAScanDeviceItem *item = nil;
        // Configure the cell...
        
        @synchronized(mPeripherals) {
            item = [mPeripherals objectAtIndex:indexPath.row];
        }
        
        NSString *deviceName = item.Peripheral.name;
        if (deviceName == nil) {
            deviceName = @"(Unknown device)";
        }
        NSRange range1 = [deviceName rangeOfString:@"AT188"];
        NSRange range2 = [deviceName rangeOfString:@"AT288"];
        NSRange range3 = [deviceName rangeOfString:@"AT388"];
        NSRange range4 = [deviceName rangeOfString:@"ATS100"];
        
        UIImage *disconverDeviceImg;
        
        if (range1.location != NSNotFound){
            disconverDeviceImg = [UIImage imageNamed:@"ic_product_at188.png"];
        }else if(range2.location != NSNotFound){
            disconverDeviceImg = [UIImage imageNamed:@"ic_product_at288.png"];
        }else if(range3.location != NSNotFound){
            disconverDeviceImg = [UIImage imageNamed:@"ic_product_at388.png"];
        }else if(range4.location != NSNotFound){
            disconverDeviceImg = [UIImage imageNamed:@"ic_product_atsl.png"];
        }else {
            disconverDeviceImg = [UIImage imageNamed:@"ic_unknown.png"];
        }
        
        
        [cell.newdeviceImg setImage:disconverDeviceImg];
        
        cell.newdevicenameLabel.text = deviceName;
        
        return cell;
    } else {
        PairedDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PairedDeviceCell" forIndexPath:indexPath];
//        [cell.pairedDeviceImg setImage:connectdeviceimg];
//        [cell.pairedStateImg setImage:connectstate];
//        cell.pairedDeviceName.text = lastDeviceName;
        DeviceSelectInfo * info = [aryDevices objectAtIndex:indexPath.row];
        [self getconnectedinfo:info.name];
        [cell.pairedDeviceImg setImage:connectdeviceimg];
        [cell.pairedStateImg setImage:connectstate];
        cell.pairedDeviceName.text = info.name;
        return cell;
        
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(actionFlag == 1)
        return;
    
    if (tableView == _newdevicetableview){
        actionFlag = 1;
        if(appDelegate.mPeripheral.state == CBPeripheralStateConnected){
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Notice" message:@"Already connected with other device." preferredStyle:UIAlertControllerStyleAlert];
            
            
            UIAlertAction* ok = [UIAlertAction
                                 actionWithTitle:@"OK"
                                 style:UIAlertActionStyleDefault
                                 handler:^(UIAlertAction * action)
                                 {
                                     [alert dismissViewControllerAnimated:YES completion:nil];
                                     actionFlag = 0;
                                 }];
            [alert addAction:ok];
            
            
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
        
        [self stopScanDevice];
        
        EAScanDeviceItem *deviceItem = [mPeripherals objectAtIndex:indexPath.row];
        
        // Connect Peripheral Device
        connectdevicename = [deviceItem.Peripheral name];
        
        isDeviceOn = 0;
        
        [self startScanDevice];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self connectDevice:indexPath.row];
        });
        
    }
}
#pragma mark - CBCentralManagerDelegate Callbacks
/*!
 *  @constant CBCentralManagerStateUnknown       State unknown, update imminent.
 *  @constant CBCentralManagerStateResetting     The connection with the system service was momentarily lost, update imminent.
 *  @constant CBCentralManagerStateUnsupported   The platform doesn't support the Bluetooth Low Energy Central/Client role.
 *  @constant CBCentralManagerStateUnauthorized  The application is not authorized to use the Bluetooth Low Energy Central/Client role.
 *  @constant CBCentralManagerStatePoweredOff    Bluetooth is currently powered off.
 *  @constant CBCentralManagerStatePoweredOn     Bluetooth is currently powered on and available to use.
 */
// Update Central Manger State...
- (void) centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"DEBUG. centeralManagerDidUpdateState:%d", (int)central.state);
    switch (central.state) {
        case CBManagerStateUnknown:
        case CBManagerStateResetting:
        case CBManagerStatePoweredOff:
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"BluetoothDisconnected" object:self];
            [self BluetoothDisconnected];
            break;
        case CBManagerStateUnsupported:
        case CBManagerStateUnauthorized:
            break;
        case CBManagerStatePoweredOn:
            [self startScanDevice];
            [self indicatorEnable:1];
            //            self.activeindicator.hidden= NO;
            //            [self.activeindicator startAnimating];
            break;
        default:
            break;
    }
}

// Discover Peripheral Devices
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    
    EAScanDeviceItem *item = nil;
    
    NSLog(@"centralManager.didDiscoverPeripheral : [%@], {%@}, [%@]  %d dBm", peripheral.name, peripheral.identifier.UUIDString, peripheral.identifier, (int)RSSI.integerValue);
    
    NSString* str1 = @"188";
    NSString* str2 = @"288";
    NSString* str3 = @"388";
    NSString* str4 = @"ATS100";
    
    NSRange str1Range = [peripheral.name rangeOfString:str1];
    NSRange str2Range = [peripheral.name rangeOfString:str2];
    NSRange str3Range = [peripheral.name rangeOfString:str3];
    NSRange str4Range = [peripheral.name rangeOfString:str4];
    
    if([peripheral.name isEqualToString:connectdevicename]){
        NSLog(@"centralManager.didDiscoverPeripheral : [%@]", peripheral.name);
        isDeviceOn = 1;
    }
    
    if ((item = [self findDeviceItemWithPeripheral:peripheral]) == nil) {
        
        if(peripheral.name == nil){
            NSLog(@"NULL mPeripherals addObject:item : [%@], {%@}, [%@]  %d dBm", peripheral.name, peripheral.identifier.UUIDString, peripheral.identifier, (int)RSSI.integerValue);
        } /*else if((str1Range.location != NSNotFound) || (str2Range.location != NSNotFound) || (str3Range.location != NSNotFound) || (str4Range.location != NSNotFound)){*/
        else if(str2Range.location != NSNotFound){
            item = [EAScanDeviceItem itemWithPeripheral:peripheral];
            @synchronized (mPeripherals) {
                [mPeripherals addObject:item];
                NSLog(@"str1Range mPeripherals addObject:item : [%@], {%@}, [%@]  %d dBm", peripheral.name, peripheral.identifier.UUIDString, peripheral.identifier, (int)RSSI.integerValue);
            }
            
        }
    }
    item.RSSI = (int)RSSI.integerValue;
    
    // Update Scan Device Table View
    [self updateScanDeviceList];
    
    // Restart Scan Device...
    [self startScanDevice];
}

// Connected Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@"centralManager.didConnectPeripheral : [%@]", peripheral.name);
    
    mDevice = [[EADeviceBluetoothLe alloc] initWithPeripheral:peripheral delegate:self];
    
    appDelegate.mPeripheral = peripheral;
}

// Failed to Connect Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    if (error) {
        NSLog(@"ERROR. centralManager.didFailToConnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
        });
    } else {
        NSLog(@"centralManager.didFailToConnectPeripheral : [%@]", peripheral.name);
    }
    
    mDevice = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

// Disconnect Peripheral Device...
- (void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    if (error) {
        NSLog(@"ERROR. centralManager.didDisconnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"BluetoothDisconnected" object:self userInfo:nil];
        [self BluetoothDisconnected];
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
            NSLog(@"ERROR. BTDiscoverViewController centralManager.didDisconnectPeripheral : [%@] - [%@]", peripheral.name, error.localizedDescription);
        });
    } else {
        [self BluetoothDisconnected];
        NSLog(@"centralManager.didDisconnectPeripheral : [%@]", peripheral.name);
    }
    
    mDevice = nil;
}

#pragma mark - ATBlEDeviceInitDelegate
- (void) didCompleteInitialize:(NSError *)error {
    if (error) {
        NSLog(@"ERROR. ATBLEDevice.didCompleteInitialize : [%@]", error.localizedDescription);
        dispatch_async(dispatch_get_main_queue(), ^{
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
            actionFlag = 0;
            return;
        });
        mDevice = nil;
    } else {
        NSLog(@"ATBLEDevice.didCompleteInitialize");
    }
    
    appDelegate.mReader = [[EAReader alloc] initWithDevice:mDevice delegate:self.readerDelegate];
    appDelegate.maskstrvalue = @"";
    dispatch_async(dispatch_get_main_queue(), ^{
        //[self.navigationController popViewControllerAnimated:YES];
        // 이 시점에서 장비 접속 완료 - 인디케이터 종료
        [HUD hide:YES];
        [HUD removeFromSuperview];
        actionFlag = 0;
        if(wrongdeviceflag == 0){
            [self.paireddevicetableview reloadData];
            [self performSegueWithIdentifier:@"Inventory" sender:nil];
        }
    });
}

#pragma mark - Internal Methods

// Start Scan Peripheral BluetoothLE Device
- (void) startScanDevice {
    
    // Make Scan Peripheral Option...
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:FALSE], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    
    bleready = 1;
    // Start Scan Peripheral Device
    [appDelegate.mCentralManager scanForPeripheralsWithServices:nil options:options];
    //    }
}

// Stop Scan Peripheral BluetoothLE Device
- (void) stopScanDevice {
    bleready = 0;
    [appDelegate.mCentralManager stopScan];
    [self indicatorEnable: 0];
}

- (void) indicatorEnable: (bool) indicator {
    dispatch_async(dispatch_get_main_queue(), ^{
        if(indicator == 1){
            self.activeindicator.hidden = NO;
            [self.activeindicator startAnimating];
        }else {
            self.activeindicator.hidden = YES;
            [self.activeindicator stopAnimating];
        }
    });
}

// Clear Scaned Peripheral BluetoothLE Device List
- (void) clearScanDevice {
    // Remote All Scan Device
    [mPeripherals removeAllObjects];
    // Update Scan Device Table View
    [self updateScanDeviceList];
}

// Update Table View
- (void) updateScanDeviceList {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.newdevicetableview reloadData];
    });
}

// Find EAScanDeviceItem With Peripheral
- (EAScanDeviceItem *) findDeviceItemWithPeripheral:(CBPeripheral *)peripheral {
    
    EAScanDeviceItem *item = nil;
    
    for (int i = 0; i < mPeripherals.count ; i++) {
        item = [mPeripherals objectAtIndex:i];
        if ([item.Peripheral isEqual:peripheral]) {
            return item;
        }
    }
    // Not Found Scan Device Item With Peripheral
    return nil;
}
- (IBAction)connectbtn:(id)sender {
    
    [self stopScanDevice];
    if(bleready == 1)
    {
        
        if (appDelegate.mPeripheral == nil){
            
            HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            HUD.labelText = @"Connecting to device";
            
            [HUD show:YES];
            
            [self.navigationController.view addSubview:HUD];
            
            NSString *uuidString = [NSString stringWithFormat:@"%@",lastDeviceAddress];
            NSUUID *nsUUID = [[NSUUID UUID] initWithUUIDString:uuidString];
            NSArray *peripherallist;
            if(lastDeviceAddress != nil)
                peripherallist = [appDelegate.mCentralManager retrievePeripheralsWithIdentifiers:@[nsUUID]];
            
            
            if(peripherallist.count>0){
                for(int i=0; i<[peripherallist count]; i++ )
                {
                    EAScanDeviceItem *item = [peripherallist objectAtIndex:i];
                    
                    NSString *itemstr = [NSString stringWithFormat:@"%@", item];
                    
                    NSRange range = [itemstr rangeOfString:lastDeviceName];
                    if (range.location != NSNotFound){
                        CBPeripheral *peripheral = [peripherallist objectAtIndex:i];
                        [appDelegate.mCentralManager connectPeripheral:peripheral options:nil];
                        appDelegate.ConnectCentralManager = appDelegate.mCentralManager;
                        NSString *uuidString = [NSString stringWithFormat:@"%@", [[item.Peripheral identifier] UUIDString]];
                        appDelegate.connectdevicename = [item.Peripheral name];
                        appDelegate.connectdeviceadd = uuidString;
                        
                        @synchronized (mPeripherals) {
                            [mPeripherals addObject:item];
                        }
//                        [self getlastdeviceinfo];
                        [self.paireddevicetableview reloadData];
                        return;
                        
                    }
                }
            }
        }else
        {
            [self disconnectDevice];
//            [self getlastdeviceinfo];
            [self.paireddevicetableview reloadData];
            return;
        }
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"ATX88N BT" message:@"BT is not power on" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction* ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
        [alert addAction:ok];
        
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}
- (void)connectDevice:(int) index {
    
    if(isDeviceOn!=1)
    {
        UIAlertView *Alert = [[UIAlertView alloc]
                              initWithTitle:@"Device Power Off" message:@"Please check the power of device you want to connect" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [Alert show];
        actionFlag = 0;
        return;
    }
    
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Connecting to device";
    
    [HUD show:YES];
    
    [self.navigationController.view addSubview:HUD];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        
        
        // Stop Scan Peripheral Device
        [self stopScanDevice];
        
        // Get Scan Device Item
        EAScanDeviceItem *item = [mPeripherals objectAtIndex:index];
        
        // Connect Peripheral Device
        
        //        dispatch_async(dispatch_get_main_queue(), ^{
        NSString *uuidString = [NSString stringWithFormat:@"%@", [[item.Peripheral identifier] UUIDString]];
        [appDelegate.mCentralManager connectPeripheral:item.Peripheral options:nil];
        appDelegate.ConnectCentralManager = appDelegate.mCentralManager;
        appDelegate.connectdevicename = [item.Peripheral name];
        appDelegate.connectdeviceadd = uuidString;
        //        });
    });
}
- (void)disconnectDevice {
    if (appDelegate.mReader != nil) {
        [appDelegate.mReader disconnect];
    }
    appDelegate.mReader = nil;
    
    // cc 종료 확인 필요........
    if(appDelegate.mPeripheral != nil){
        [appDelegate.mCentralManager cancelPeripheralConnection:appDelegate.mPeripheral];
        
        appDelegate.mPeripheral = nil;
    }
}
#pragma mark - NSNotification
- (void)BluetoothDisconnected {
    wrongdeviceflag = 1;
    appDelegate.mReader = nil;
    appDelegate.mPeripheral = nil;
    [self disconnectDevice];
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [HUD removeFromSuperview];
        [AppDelegate dismissGlobalHUD];
        NSLog(@"BTDiscover BluetoohDisconnected");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Bluetooth" message:@"Bluetooth device is disconnected" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
    
}
- (void)BluetoothDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [HUD hide:YES];
        [HUD removeFromSuperview];
        [AppDelegate dismissGlobalHUD];
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
    
}
- (void) wrongdeviceconnected:(NSNotification *)notification {
    NSLog(@"BTDiscoverViewController - wrongdeviceconnected");
    wrongdeviceflag = 1;
    [self disconnectDevice];
}
@end

