Skip to content

Instantly share code, notes, and snippets.

- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
if ([self isIgnorePeripheral:RSSI]) {
return;
}
if (peripheral) {
if (![self.peripherals containsObject:peripheral]) {
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state != CBCentralManagerStatePoweredOn) {
return;
}
[self scan:central];
}
- (void)scan:(CBCentralManager *)central {
CBUUID *uuid = [CBUUID UUIDWithString:kServiceUUID];
NSDictionary *options = @{CBCentralManagerOptionRestoreIdentifierKey : CENTRAL_IDENTIFIER_KEY};
_centralManager = [[CBCentralManager alloc] initWithDelegate:self
queue:_serialQueue
options:options];
- (void)sendData:(NSData *)sendMsg
dataIndex:(NSInteger)sendMsgIndex {
// First up, check if we're meant to be sending an EOM
static BOOL sendingEOM = NO;
NSString *logMessage = nil;
const int NOTIFY_MTU = 20;
const float SendMessageTimeInterval = 0.2f;
if (sendingEOM) {
- (void)peripheralManager:(CBPeripheralManager *)peripheral
didReceiveWriteRequests:(NSArray <CBATTRequest *>*)requests {
for (CBATTRequest *request in requests) {
if (request.value) {
NSString *value = [[NSString alloc] initWithData:request.value encoding:NSUTF8StringEncoding];
if ([_delegate respondsToSelector:@selector(BLEPeripheralComponentReceiveMessage:message:)]) {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.delegate BLEPeripheralComponentReceiveMessage:self message:value];
- (void)peripheralManager:(CBPeripheralManager *)peripheral
central:(CBCentral *)central
didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
if (![self.centralM containsObject:central]) {
[self.centralM addObject:central];
}
[self updateCharacteristicValue];
[self stopAdvertising];
}
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral
error:(NSError *)error {
if (error) {
// error handle
return;
}
// start advertising
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral
didAddService:(CBService *)service
error:(NSError *)error {
if (error) {
return;
}
[self startAdvertising];
}
- (void)setupService {
// Step 1: Create CharacteristicUUID
CBUUID *characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];
CBMutableCharacteristic *characteristicM = [[CBMutableCharacteristic alloc]
initWithType:characteristicUUID
properties:CBCharacteristicPropertyNotify |
CBCharacteristicPropertyRead |
CBCharacteristicPropertyWrite |
CBCharacteristicPropertyWriteWithoutResponse
value:nil
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
// stopAdvertising
return;
}
// setup service
[self setupService];
}