BleSearchViewController.m 8.59キロバイト
//
//  BleSearchViewController.m
//  jacket_ios
//
//  Created by ドラッサル 亜嵐 on 2016/04/27.
//  Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//

#import "BleSearchViewController.h"
#import "BleControl.h"
#import "BleSearchResultTableViewController.h"
#import "SettingsController.h"
#import "Operation.h"
#import "jacket_test_ios-Swift.h"

@interface BleSearchViewController ()

@end

NSString * const  UUIDPrefKey = @"UUIDPrefKey";

@implementation BleSearchViewController
@synthesize ble;
@synthesize protocol;
BleControl *cv;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    ble = [[BLE alloc] init];
    [ble controlSetup];
    ble.delegate = self;
    
    self.mDevices = [[NSMutableArray alloc] init];
    self.mDevicesName = [[NSMutableArray alloc] init];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UUIDPrefKey];
    }
    
    //Retrieve saved UUID from system
    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
    if ([self.lastUUID isEqualToString:@""])
    {
        [btnConnectLast setEnabled:NO];
    }
    else
    {
        [btnConnectLast setEnabled:YES];
    }
    
    protocol = [[BleProtocol alloc] init];
    protocol.ble = ble;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"idSegueBleDeviceList"])
    {
        BleSearchResultTableViewController *vc = [segue destinationViewController];
        vc.BLEDevices = self.mDevices;
        vc.BLEDevicesName = self.mDevicesName;
        vc.ble = ble;
        vc.protocol = protocol;
    }
    else if ([[segue identifier] isEqualToString:@"idSegueBleDevice"])
    {
        cv = [segue destinationViewController];
        cv.ble = ble;
        cv.protocol = protocol;
    }
}

- (void)connectionTimer:(NSTimer *)timer
{
    showAlert = YES;
    [btnConnect setEnabled:YES];
    
    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
    
    if ([self.lastUUID isEqualToString:@""])
    {
        [btnConnectLast setEnabled:NO];
    }
    else
    {
        [btnConnectLast setEnabled:YES];
    }
    
    if (ble.peripherals.count > 0)
    {
        if(isFindingLast)
        {
            int i;
            for (i = 0; i < ble.peripherals.count; i++)
            {
                CBPeripheral *p = [ble.peripherals objectAtIndex:i];
                
                if (p.identifier.UUIDString != NULL)
                {
                    //Comparing UUIDs and call connectPeripheral is matched
                    if([self.lastUUID isEqualToString:p.identifier.UUIDString])
                    {
                        showAlert = NO;
                        [ble connectPeripheral:p];
                    }
                }
            }
        }
        else
        {
            [self.mDevices removeAllObjects];
            [self.mDevicesName removeAllObjects];
            
            int i;
            for (i = 0; i < ble.peripherals.count; i++)
            {
                CBPeripheral *p = [ble.peripherals objectAtIndex:i];
                
                if (p.identifier.UUIDString != NULL)
                {
                    [self.mDevices insertObject:p.identifier.UUIDString atIndex:i];
                    if (p.name != nil) {
                        [self.mDevicesName insertObject:p.name atIndex:i];
                    } else {
                        [self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
                    }
                }
                else
                {
                    [self.mDevices insertObject:@"NULL" atIndex:i];
                    [self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
                }
            }
            showAlert = NO;
            [self performSegueWithIdentifier:@"idSegueBleDeviceList" sender:self];
        }
    }
    
    if (showAlert == YES) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"No BLE Device(s) found."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
    [activityScanning stopAnimating];
}

- (IBAction)btnConnectClicked:(id)sender
{
    if (ble.activePeripheral)
        if(ble.activePeripheral.state == CBPeripheralStateConnected)
        {
            [[ble CM] cancelPeripheralConnection:[ble activePeripheral]];
            return;
        }
    
    if (ble.peripherals)
        ble.peripherals = nil;
    
    [btnConnect setEnabled:false];
    [btnConnectLast setEnabled:NO];
    [ble findBLEPeripherals:3];
    
    [NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];
    
    isFindingLast = false;
    [activityScanning startAnimating];
}

- (IBAction)lastClick:(id)sender {
    if (ble.peripherals) {
        ble.peripherals = nil;
    }
    
    [btnConnect setEnabled:false];
    [btnConnectLast setEnabled:NO];
    [ble findBLEPeripherals:3];
    
    [NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];
    
    isFindingLast = true;
    [activityScanning startAnimating];
}

- (void) bleDidConnect
{
    NSLog(@"->DidConnect");
    
    self.lastUUID = ble.activePeripheral.identifier.UUIDString;
    [[NSUserDefaults standardUserDefaults] setObject:self.lastUUID forKey:UUIDPrefKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
    if ([self.lastUUID isEqualToString:@""]) {
        [btnConnectLast setEnabled:NO];
    } else {
        [btnConnectLast setEnabled:YES];
    }
    
    [activityScanning stopAnimating];
    
    [self populatePcbInfo];
    
    [SettingsController show:(NSString *)protocol navigationController:self.navigationController];
}

- (void)bleDidDisconnect
{
    NSLog(@"->DidDisconnect");
    
    [activityScanning stopAnimating];
    [self.navigationController popToRootViewControllerAnimated:true];
}

- (void)populatePcbInfo {
    if([Operation sharedOperation].pcbDeviceId == nil) {
        [protocol putData:@"infoDeviceId" data:nil];
    } else if([Operation sharedOperation].pcbDeviceType == nil) {
        [protocol putData:@"infoDeviceType" data:nil];
    } else if([Operation sharedOperation].pcbDeviceModel == nil) {
        [protocol putData:@"infoDeviceModel" data:nil];
    } else if([Operation sharedOperation].pcbDeviceOs == nil) {
        [protocol putData:@"infoDeviceOs" data:nil];
    }
}

- (void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
    
    NSLog(@"data!!!%s", data);
    
    for(int i = 0; i < length; i++) {
        if((data[i] < 32) || (data[i] > 127)) {
            data[i] = ' ';
        }
    }
    NSString* dataString = [NSString stringWithCString: (const char *)data encoding:NSUTF8StringEncoding];
    dataString = [dataString substringToIndex:length];
    
   
    NSLog(@"->DidReceiveData- %@",dataString);
   
    if([dataString hasPrefix:@"ii"]) {
        [Operation sharedOperation].pcbDeviceId = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
        [self populatePcbInfo];
    } else if ([dataString hasPrefix:@"it"]) {
        [Operation sharedOperation].pcbDeviceType = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
        [self populatePcbInfo];
    } else if ([dataString hasPrefix:@"im"]) {
        [Operation sharedOperation].pcbDeviceModel = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
        [self populatePcbInfo];
    } else if ([dataString hasPrefix:@"io"]) {
        [Operation sharedOperation].pcbDeviceOs = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
        [self populatePcbInfo];
    }
    
    [protocol parseData:data length:length];
   /* for iot Demo */
    [[Caller sheardInstance] proximityNofiticationTrigger];
     /* for iot Demo end */
}

- (void) bleDidUpdateRSSI:(NSNumber *) rssi
{
}

- (NSString *)getUUIDString:(CFUUIDRef)ref {
    NSString *str = [NSString stringWithFormat:@"%@", ref];
    return [[NSString stringWithFormat:@"%@", str] substringWithRange:NSMakeRange(str.length - 36, 36)];
}

@end