Simple, block-based, lightweight library over CoreBluetooth. Will clean up your Core Bluetooth related code.

Overview

LGBluetooth

Simple, block-based, lightweight library over CoreBluetooth.

Steps to start using

  1. Drag and Drop it into your project

  2. Import "LGBluetooth.h"

  3. You are ready to go!

Usage

For example we have a peripheral which has "5ec0" service, with 3 characteristics

  • "cef9" characteristic is writable
  • "f045" characteristic is readable
  • "8fdb" characteristic is readable
- (IBAction)testPressed:(UIButton *)sender
{
    [[LGCentralManager sharedInstance] scanForPeripheralsByInterval:4
                                                         completion:^(NSArray *peripherals)
     {
         if (peripherals.count) {
             [self testPeripheral:peripherals[0]];
         }
     }];
}

- (void)testPeripheral:(LGPeripheral *)peripheral
{   
    // First of all, opening connection
    [peripheral connectWithCompletion:^(NSError *error) {
        // Discovering services of peripheral
        [peripheral discoverServicesWithCompletion:^(NSArray *services, NSError *error) {
            // Searching in all services, our - 5ec0 service
            for (LGService *service in services) {
                if ([service.UUIDString isEqualToString:@"5ec0"]) {
                    // Discovering characteristics of 5ec0 service
                    [service discoverCharacteristicsWithCompletion:^(NSArray *characteristics, NSError *error) {
                        __block int i = 0;
                        // Searching writable characteristic - cef9
                        for (LGCharacteristic *charact in characteristics) {
                            if ([charact.UUIDString isEqualToString:@"cef9"]) {
                                [charact writeByte:0xFF completion:^(NSError *error) {
                                    if (++i == 3) {
                                        [peripheral disconnectWithCompletion:nil];
                                    }
                                }];
                            } else {
                                // Otherwise reading value
                                [charact readValueWithBlock:^(NSData *data, NSError *error) {
                                    if (++i == 3) {
                                        [peripheral disconnectWithCompletion:nil];
                                    }
                                }];
                            }
                        }
                    }];
                }
            }
        }];
    }];
}

After running code we can see the result.


In this example I'm scanning peripherals for 4 seconds. After which I am passing first peripheral to test method.

Test method connects to peripheral, discoveres services, discoveres characteristics of "5ec0" service. After which reads "f045", "8fdb", and writes 0xFF to "cef9" and disconnects from peripheral.

Here is the log from console

Connection with error - (null)
Service discovered - Battery
Service discovered - Current Time
Service discovered - Unknown (5ec0)
Characteristic discovered - Unknown (cef9)
Characteristic discovered - Unknown (f045)
Characteristic discovered - Unknown (8fdb)
Characteristic - Unknown (cef9) wrote with error - (null)
Characteristic - Unknown (f045) value - 1234567890 error - 
Characteristic - Unknown (8fdb) value - 11111111111 error - (null)
Disconnect with error - (null)

Alternative use

You can make basic read/write via LGUtils class. Note : This methods do NOT need active connection to peripheral, they will open a connection if it doesn't exists.

Read example

        [LGUtils readDataFromCharactUUID:@"f045"
                             serviceUUID:@"5ec0"
                              peripheral:peripheral
                              completion:^(NSData *data, NSError *error) {
                                  NSLog(@"Data : %s Error : %@", (char *)[data bytes], error);
                              }];

Write example

        int8_t dataToWrite = 0xFF;
        [LGUtils writeData:[NSData dataWithBytes:&dataToWrite length:sizeof(dataToWrite)]
               charactUUID:@"cef9"
               serviceUUID:@"5ec0"
                peripheral:peripheral completion:^(NSError *error) {
                    NSLog(@"Error : %@", error);
                }];

Reasons of using LGBluetooth

As we know CoreBluetooth is very hard to use - The methods of objects in Core bluetooth are messy

For example connectPeripheral:options: is written in CBCentralManager, discoverCharacteristics:forService is written in Peripheral, writeValue:forCharacteristic:type, readValueForCharacteristic are also in Peripheral

This messy code makes CoreBluetooth development really painfull. For example if you need to read characteristic value, you need to call "connect" on central object, wait for Central delegate callback, After that call "discover services", wait peripheral delegate callback, "discover characteristic" which you planned and wait for delegate callback, "readValue" and again wait for delegate callback. What will happen if your program will make 2 connections at once? Handling such cases makes messy code, and raises hundred of bugs.

Don't worry, now you can forgot about that hell - LGBluetooth uses blocks for callbacks, you can start using modern code and hierarchical calls.

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries installation in your projects.

Podfile

pod "LGBluetooth", "~> 1.1.5"

LICENSE

LGBluetooth is under MIT License (see LICENSE file)
Comments
  • Sequential 'connects' fail

    Sequential 'connects' fail

    I'm using a workflow where I end up in a view controller with a 'connect' and 'disconnect' button.

    I can always connect/disconnect on the first attempt, however, subsequent attempts never connect. I need to go back to my listview, in order to re-scan for peripherals - and then try to connect again later when the peripheral has been re-discovered.

    What could be going on?

    Thanks! -SJ

    opened by sureshjoshi 6
  • Cannot discover characteristics

    Cannot discover characteristics

    When I run the code only thing outputted is this: 2015-09-01 11:44:22.415 LGBluetoothExample[6344:762493] Connection with error - (null) 2015-09-01 11:44:22.714 LGBluetoothExample[6344:762493] Service discovered - FFE0

    Is there something I'm missing? Could do with a bit of insight on this.

    opened by edelibasi 3
  • Avoid crashes & A better solution for the issue #6.

    Avoid crashes & A better solution for the issue #6.

    Hi,

    Thanks for your project!

    During my usage, I've improved some details, and I've been using my version for more than 3 months, it's very stable now.

    Best regards,

    opened by CocoaBob 2
  • How can we scan indefinitely, and get a callback on each advertisement?

    How can we scan indefinitely, and get a callback on each advertisement?

    As the question asks, how can we scan indefinitely, and get a callback on each advertisement?

    The scanWithPeripherals() call doesn't have any callbacks on device discovery. Also, I can't see any way to otherwise get some advertisement discovery information (other to maybe put a KVO on the peripherals variable?)

    opened by sureshjoshi 2
  • Changed deprecated iOS8 RSSI CoreBluetooth call.

    Changed deprecated iOS8 RSSI CoreBluetooth call.

    Changed deprecated iOS8 RSSI CoreBluetooth call.

    peripheral.RSSI and peripheralDidUpdateRSSI were deprecated in iOS8 - now need to use the didReadRSSI API.

    opened by sureshjoshi 0
  • crashed after Restart Bluetooth for several times

    crashed after Restart Bluetooth for several times

    after Restart Bluetooth for several times,app crashed at [self.cbCharacteristic.service.peripheral writeValue:data forCharacteristic:self.cbCharacteristic type:type]; it seems that "self.cbCharacteristic.service" exist,but the "self.cbCharacteristic.service.peripheral" lost.so it crashed.

    opened by sanfang 0
  • write command not return expected result

    write command not return expected result

    i tried to read temperature from foramed devices with command 0x26 i can pairing and read info (name ,version , manufacturer) but i cann't write command 0x26 to read result

    // Scaning 4 seconds for peripherals [[LGCentralManager sharedInstance] scanForPeripheralsByInterval:10 completion:^(NSArray *peripherals) { // If we found any peripherals sending to test for (LGPeripheral *per in peripherals) { if ([per.UUIDString isEqualToString:@"2FF2DAFC-D4D5-4929-8E80-4CA23C56EEF2"]) {

             const uint16_t bytes[] = {0x26};
             NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
                
                 [LGUtils writeData:data
                        charactUUID:@"00001524-1212-efde-1523-785feabcd123"
                        serviceUUID:@"00001523-1212-efde-1523-785feabcd123"
                         peripheral:per completion:^(NSError *error) {
                             NSLog(@"Error : %@", error);
                             
                             [LGUtils readDataFromCharactUUID:@"00001524-1212-efde-1523-785feabcd123"
                                                  serviceUUID:@"00001523-1212-efde-1523-785feabcd123"
                                                   peripheral:per
                                                   completion:^(NSData *data, NSError *error) {
                                                       NSLog(@"Data : %s Error : %@", (char *)[data bytes], error);
                                                   }];
                         }];
             
                 
         }
             NSLog(@"name:%@ UUID:%@",per.name,per.UUIDString);
         }
         
         
    
     }];
    
    opened by mdsalah990 0
  • Problem with writeData

    Problem with writeData

    I'm having some problems while writing data

    >       Byte bytes[] = {0x00, 0x01, 0x04, 0xd2};
    >       NSData *data = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];  // Funziona
    > 
    >       
    >       [LGUtils writeData:data
    >              charactUUID:@"01080000-0000-55f8-0840-5404a6b91b26"
    >              serviceUUID:@"01000000-0000-55f8-0840-5404a6b91b26"
    >               peripheral:peripheral completion:^(NSError *error) {
    >                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    >                 NSLog(@"Scrittura dati - %@ %d Error : %@", data, data.length, error);
    >                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    >                   [LGUtils readDataFromCharactUUID:@"01080000-0000-55f8-0840-5404a6b91b26"
    >                                        serviceUUID:@"01000000-0000-55f8-0840-5404a6b91b26"
    >                                         peripheral:peripheral
    >                                         completion:^(NSData *data, NSError *error) {
    >                                           NSLog(@"%@ Data lenght %d : Error : %@", data, data.length, error);
    >                                         }];
    >                 });
    >               }];
    

    When I read the data I get the same value I wrote, instead the expected response from the device (in this case 0x000100000000)

    I make a test with DarkBlue, an app from GitHub, which use the standard bluetooth library, and this code works:

      Byte bytes[] = {0x00, 0x01, 0x04, 0xd2};
      NSData *wrData = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];  // Funziona
    
      NSLog(@"DEBUG ... %@", wrData);
    
      [self.peripheral writeValue:wrData forCharacteristic:self.defaultBTServer.selectCharacteristic type:CBCharacteristicWriteWithResponse];
      [self readAction];
    

    The readAction method is a call to readValue, and the response from the device is as expected. Can you help me to figure out what is wrong with my code ?

    opened by marco-ni 2
  • LGUtils and LGPeripheral cannot be used together

    LGUtils and LGPeripheral cannot be used together

    When I set a notification on the Peripheral's characteristic manually, after being called once (working), I then perform some operations using LGUtils as a utility method to ensure that all services/characteristics are discovered, and that I'm connected - however, this wipes out my notification value next time around.

    opened by sureshjoshi 1
Releases(1.1.5)
Owner
null
SwiftyBluetooth - Closures based APIs for CoreBluetooth.

SwiftyBluetooth Closures based APIs for CoreBluetooth. Features Replace the delegate based interface with a closure based interface for every CBCentra

Jordane Belanger 181 Jan 2, 2023
CombineCoreBluetooth is a library that bridges Apple's CoreBluetooth framework and Apple's Combine framework

CombineCoreBluetooth is a library that bridges Apple's CoreBluetooth framework and Apple's Combine framework, making it possible to subscribe to perform bluetooth operations while subscribing to a publisher of the results of those operations, instead of relying on implementing delegates and manually filtering for the results you need.

Starry 74 Dec 29, 2022
A small library that adds concurrency to CoreBluetooth APIs.

AsyncBluetooth A small library that adds concurrency to CoreBluetooth APIs. Features Async/Await APIs Queueing of commands Data conversion to common t

Manuel Fernandez 83 Dec 28, 2022
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.

ExtendaBLE Introduction ExtendaBLE provides a very flexible syntax for defining centrals and peripherals with ease. Following a blocks based builder a

Anton 94 Nov 29, 2022
Build your own 'AirTags' 🏷 today! Framework for tracking personal Bluetooth devices via Apple's massive Find My network.

OpenHaystack is a framework for tracking personal Bluetooth devices via Apple's massive Find My network.

Secure Mobile Networking Lab 5.8k Jan 9, 2023
Bluejay is a simple Swift framework for building reliable Bluetooth LE apps.

Bluejay is a simple Swift framework for building reliable Bluetooth LE apps. Bluejay's primary goals are: Simplify talking to a single Bluetooth LE pe

Steamclock Software 1k Dec 13, 2022
RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant.

RxBluetoothKit is a Bluetooth library that makes interaction with BLE devices much more pleasant. It's backed by RxSwift and CoreBluetooth and it prov

Polidea 1.3k Jan 6, 2023
Fluetooth - Flutter library for sending bytes to Bluetooth devices on Android/iOS

A Flutter library for sending bytes to Bluetooth devices. Available on Android a

Iandi Santulus 1 Jan 2, 2022
The Bluetooth LE library for iOS and Mac. 100% Swift.

iOS-BLE-Library An in-development Bluetooth Low Energy Library by Nordic Semiconductor to interact with the , which is not complicated, but requires w

Nordic Semiconductor 6 Dec 19, 2022
iOS Bluetooth LE framework

Features A futures interface replacing protocol implementations. Timeout for Peripheral connection, Service scan, Service + Characteristic discovery a

Troy Stribling 696 Dec 25, 2022
Omnipod Bluetooth PumpManager For Loop

OmniBLE Omnipod Bluetooth PumpManager For Loop Status This module is at the very beginning stages of development and does not even compile yet. DO NOT

Randall Knutson 20 Apr 21, 2022
Diabetes: test the FreeStyle Libre glucose sensor as a Bluetooth Low Energy device, even directly from an Apple Watch.

Since the FreeStyle Libre 2 / 3 glucose sensors are Bluetooth Low Energy devices, I am trying to leverage their capabilities to implement something ne

Guido Soranzio 6 Jan 2, 2023
Bluetooth mapping in Swift

Bluetonium is part of the E-sites iOS Suite. Bluetonium is a Swift Library that makes it easy to communicate with Bluetooth devices. Features ?? Servi

E-sites 165 Nov 20, 2022
The easiest way to use Bluetooth (BLE )in ios,even bady can use.

The easiest way to use Bluetooth (BLE )in ios,even bady can use.

刘彦玮 4.6k Dec 27, 2022
Bluetooth mesh messaging SDK for apps

Berkanan SDK Berkanan SDK enables Bluetooth mesh messaging between nearby apps. It's the framework used by Berkanan Messenger (Product Hunt, TechCrunc

Zsombor Szabo 189 Jan 1, 2023
MiniVendingMachine - SwiftUI demo Apple Watch app to open a mini vending machine via bluetooth

Mini Vending Machine Use Apple Watch to open vending machine cells. Note: This a

CGH 3 Apr 8, 2022
A very simple library to discover and retrieve data from nearby devices (even if the peer app works at background).

Discovery: A simple library to discover and retrieve data from nearby devices. Discovery is a very simple but useful library for discovering nearby de

Ömer Faruk Gül 412 Dec 19, 2022
ScanID - Homework iOS project to scan IDs MRZ code

ScanID Homework iOS project to scan IDs MRZ code Requirements for mobile applica

Artūrs Āre 0 Jan 28, 2022
Automate your espresso machine

OhMyShot: Automate your espresso machine! OhMyShot! is an iOS app that supercharges your classic espresso machine. It provides gravimetric control a s

Nikitas Rontsis 5 Oct 21, 2022