CFRunL oop в отдельной теме - PullRequest
       105

CFRunL oop в отдельной теме

0 голосов
/ 17 марта 2020

Какой подход необходим для перевода следующей программы Obj- C Foundation и CoreBluetooth CLI, чтобы устройства Bluetooth печатались в отдельном потоке.

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#include <stdio.h>

@interface BluetoothDevicePrinter: NSObject
<CBCentralManagerDelegate, CBPeripheralDelegate>

@property (strong, nonatomic) CBCentralManager * manager;

- (void)setup;
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
- (void)startScan;
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
@end

@implementation BluetoothDevicePrinter

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"New Device: %@\n", [peripheral name]);
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)manager
{
    if ([manager state] == CBManagerStatePoweredOn)
    {
        [self startScan];
    }
}

- (void) startScan
{
    printf("Start scanning\n");
    [_manager scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@"180D"]] options:nil];
}

- (void)setup
{
    _manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

@end

int main(int argc, const char * argv[])
{

    BluetoothDevicePrinter *btPrinter = [[BluetoothDevicePrinter alloc]init];
    [btPrinter setup];
    CFRunLoopRun();
    return 0;
}

Требуемый основной l oop смоделированный в псевдообъекте c будет выглядеть примерно так:

int main(int argc, const char * argv[])
{
    BluetoothDevicePrinter *btPrinter = [[BluetoothDevicePrinter alloc]init];
    CFRunLoopInNewThread(
                         Target: btPrinter
                   pointOfEntry: setup);
    while(true){}
    return 0;
}

с while(true){} моделированием другого процесса / запуска l oop

ИЛИ

Является ли это неправильным подходом полностью?

Конечная цель состоит в том, чтобы включить функцию Bluetooth и сканирование устройств, включенных в функцию и вызываемых отдельной C программой.

1 Ответ

0 голосов
/ 17 марта 2020

Правильный ответ представляется , это неправильный подход полностью . Вместо CFRunLoop CBCentralManager следует инициализировать dispatch_queue_t

. В этом вопросе возникает та же проблема, но в обертке Obj- C python, а не в c

Я был удивлен, обнаружив подобный вопрос без ответа . Этот вопрос относится только к AWS SDK.

Метод initWithDelegate для CBCentralManager имеет параметр queue, скрывающийся в поле зрения. Для запуска в отдельном потоке подойдут следующие варианты:

[[CBCentralManager alloc] initWithDelegate:<#DElEGATE#> queue: <#DISPATCH_QUEUE#>];

Для простоты добавление этого к main будет выглядеть примерно так:

int main(int argc, const char * argv[])
{
    btPrinter = [[BluetoothDevicePrinter alloc]init];
    dispatch_queue_t bleQueue = dispatch_queue_create("ble_device_list", NULL);
    btPrinter.manager = [[CBCentralManager alloc] initWithDelegate:btPrinter queue: bleQueue];
    while(1)
    return 0;
}
...