1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| - (void)viewDidLoad
{
[super viewDidLoad];
[self startConnection];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)startConnection
{
self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)openConnection
{
static NSString * const kServiceUUID = @"FFE0";
[self.manager scanForPeripheralsWithServices:@[ [CBUUID UUIDWithString:kServiceUUID] ] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO }];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
[self logMessage:[NSString stringWithFormat:@"centralManagerDidUpdateState:%d", central.state]];
if (self.connected && central.state < CBCentralManagerStatePoweredOn) {
[self resetConnection];
} else if (!self.connected && central.state >= CBCentralManagerStatePoweredOn) {
[self openConnection];
}
}
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI
{
if(peripheral.name==nil)
{
[self startConnection];}
else
{
self.found = TRUE;
[self.manager stopScan];
self.peripheral = peripheral; // Otherwise gets released
[self.manager connectPeripheral:peripheral options:nil];
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[peripheral setDelegate:self];
[peripheral discoverServices:nil];
}
- (void)centralManager:(CBCentralManager *)central
didFailToConnectPeripheral:(CBPeripheral *)peripheral
error:(NSError *)error
{}
- (void)centralManager:(CBCentralManager *)central
didDisconnectPeripheral:(CBPeripheral *)peripheral
error:(NSError *)error;
{}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
for (CBService *service in peripheral.services) {
NSString *UUIDString = CFBridgingRelease(CFUUIDCreateString(NULL, CFBridgingRetain(service.UUID)));
[peripheral discoverCharacteristics:nil forService:service];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
NSString *UUIDString = CFBridgingRelease(CFUUIDCreateString(NULL, CFBridgingRetain(service.UUID)));
for (CBCharacteristic *characteristic in service.characteristics) {
NSData * data ;
data=[@"1" dataUsingEncoding:NSUTF8StringEncoding];
[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
} |
Partager