macoscachingbluetoothcore-bluetoothiobluetooth

Clearing CoreBluetooth GATT cache without removing bond


I have an iOS app acting as peripheral and an OS X app acting as a central, using the CoreBluetooth framework. The OS X app connects to the iOS app and they bond by reading an encrypted characteristic and entering a random code. Everything works fine, up until the point the iOS app is restarted. From then on, every time I connect to the iOS device and try to read any of its characteristics, it returns a "Handle is invalid"-error. The only way to fix this is by removing the device from OS X' Bluetooth preferences and reinitiate the bonding process.

I suspect this issue is caused by OS X' caching of my device's services and characteristics, seeing that the issue doesn't appear when I'm using two iOS devices to connect to each other after rebooting one.

What I'm looking for is a way to clear OS X' cache of my services and characteristics. I'm familiar with the method of deleting com.apple.Bluetooth.plist and restarting the blued process/turning Bluetooth on/off. (Does blued cache ATT values, and how to clear the cache? and How can I clear the CoreBluetooth cache on MacOS?)

However, deleting com.apple.Bluetooth.plist requires me to bond with the iOS device again and enter a code. Is there any way to clear the cache, but only do so with the services/characteristics related to my app?


Solution

  • Turns out it was easier than I thought. In com.apple.Bluetooth.plist, there's a CoreBluetoothCache key containing a dictionary with some cached services and stuff. The tricky part was editing the cache without blued writing all over it. Anyway, this is the way to go (in Terminal):

    sudo defaults write /Library/Preferences/com.apple.Bluetooth CoreBluetoothCache -dict
    sudo launchctl unload /System/Library/LaunchDaemons/com.apple.blued.plist
    sudo launchctl load /System/Library/LaunchDaemons/com.apple.blued.plist
    

    After this, CoreBluetooth actually rediscovers the services and reads the characteristics the right way.