It has been more than a year since I came to write an article. Today, it is windy and crisp. Let me summarize some personal problems about BLE Bluetooth

What is classic Bluetooth, what is BLE Bluetooth, what is dual-mode Bluetooth

A. Classic Bluetooth:

1), voice transmission: such as Bluetooth headphones, Bluetooth speakers. Bluetooth was designed to transmit sound, so it is the perfect choice for close range audio transmission. There are also wifi-based audio transmission solutions, such as Airplay, but WIFI power consumption is much greater than Bluetooth, and devices cannot be portable. Therefore, fixed speakers with WIFI, mobile such as headphones, portable speakers are all based on the classic Bluetooth protocol.

2), transfer a large amount of data: such as some industrial control scenarios, the use of Android or Linux master, bluetooth remote control device, can use the classic Bluetooth SPP protocol, as a wireless serial port use. The speed is much faster than BLE transmission.

B, BLE Bluetooth:

1) Low power consumption, small data amount, such as remote control (mouse, keyboard), sensing equipment (heartbeat band, sphygmomanometer, temperature sensor, shared bike lock, smart lock, anti-loss device, indoor positioning).

2) At present, it is the most cost-effective means of mobile phone and intelligent hardware communication. The straight-line distance is about 50 meters, and a no. 5 battery can last for one year. The transmission mode is cheap and far more practical than WIFI, 4G and other communication protocols with large data volume. Although the Bluetooth is a little closer, but it is better than the direct phone, the price is super cheap. Take indoor positioning as an example, each store in the shopping mall hanging a Bluetooth beacon, can be done to the mobile phone accuracy of 10 meters indoor positioning, bluetooth 5.1 in the future can achieve more centimeter-level indoor positioning.

C. Dual-mode Bluetooth:

1) Smart TV remotes: Many smart TV remotes come with voice recognition and require classic Bluetooth to transmit sound. For complex keys, such as those that aren’t on the original keyboard list, the classic Bluetooth HID key protocol won’t work, and BLE will be the proprietary protocol.

2) Noise-canceling headphones: Many noise-canceling headphones use APP to adjust the noise reduction effect, which is also a proprietary communication protocol realized through BLE.

Problems encountered during development

1. Matching lists disappear
  • BluetoothAdapter.getDefaultAdapter().getBondedDevices(); This method is to get the list of devices that have been pair, sometimes notremoveBondThere is a device, but it disappears under certain circumstances, which isgetBondedDevices().size=0

The current tendency is that the system does something

2. When scanning BLE devices, there is a chance that the entire App page card will be found due to BLE scanning
3. Basic BLE operations cause BLE Crash
Error: status =133 when connecting to BLE
  • Repeatable method: disconnect and connect continuously
  • Note: Connect BLE. If BLE is already connected to another device, then status 133 is normal, but our tablet has a high probability of this happening
5. When Bluetooth scanning is enabled when Bluetooth is already on,getBluetoothLeScanner()==nullThen the scan cannot be enabled
6. No response occurs during the establishment and interception of Bluetooth
  • Description of bluetooth connection process: Start BLE Scan –> Get target device –> Start Pair –> Succeed –> Start Connection –> Connect successful –>changeMTU–>onMtuChanged() This is the built-in method of GattCallback, Callback –> Then start gat.DiscoverServices (); –> Key negotiation –> real connection status
  • Problem found: When manually calling changeMTU, the onMtuChanged method gets stuck in the middle with no callback

Recommendations for optimization in development

  • 1. Bluetooth scanning device

I realize the way is by opening a thread pool, this is Executors newSingleThreadExecutor (),

/** * How to understand: * 1. A new task will be placed in corePool, the core thread pool, the size is 1, where corePoolSize=maximumPoolSize=1 * 2. When the core thread pool is full, it will be placed on the LinkedBlockingQueue. If the LinkedBlockingQueue is a bounded queue, a bounded blocking queue composed of a linked list structure, and it is also full. size=Integer.MAX_VALUE * 3. Create a new task in the thread pool smaller than the maximum until the  maximum thread pool is full * 4. It will go to the rejection queue to see what kind of rejection plan it is, and then just like that * 5. Because defaultHandler = new AbortPolicy(); it is possible to throw an exception, although this chance is small * 6. The execution time of the execute method is usually a slow process. If it is a fast process, you will not be placed in the thread pool, So I think this is suitable for download initialization */ /** * how to understand: * 1. A new task is placed in the corePool, the core thread pool, of size 1, where corePoolSize=maximumPoolSize=1 * 2. When the core thread pool is full, it is placed on the LinkedBlockingQueue. If LinkedBlockingQueue is a bounded queue, a bounded blocking queue made up of a linked list structure, it's also full. Size = integer.MAX_VALUE * 3. Create a new task in the thread pool that is less than the maximum value until the maximum thread pool is full * 4. * 5. Because defaultHandler = new AbortPolicy(); It is possible to throw an exception, although this is a small chance * 6. The execution time of the execute method is usually a slow process. If it's a fast process, you won't be put in the thread pool, so I think this is suitable for download initialization */Copy the code

  • 2, in the actual process, BLE has occurred false connection, so it is critical to judge whether BLE is in the state of connection

Mainly through the reflection to obtain connection state Method Method. = bluetoothDeviceClass getDeclaredMethod (” isConnected (Class []) null);

  • 3, BluetoothAdapter. GetDefaultAdapter (.) getBluetoothLeScanner ()

When BLE is off, this will be null, but I actually found during the development process, it will also be NULL, so we need to judge null, and also need to judge when scanning the device, otherwise, the whole child thread crash, no response

  • 4. As for the problem of scanning pairs all the time, since The Android system is different, it may happen that pairs are always scanned on some boards.

I suggest that if the Pair fails too many times, you can secretly turn BLE on and off to solve the problem

  • 5. No response occurs in the process of bluetooth interception

BLE can be sneaked on and off to solve the problem, I know about the specific reason, but I am not sure, so I will not post the reason

  • 6. I have seen many open source projects use this method to determine if BLE is connected

But it’s not so good. For my reasons, it’s ok to call a connection failure here, but what? How about a successful connection? If the project doesn’t involve key negotiation, then it should work. However, all the commercial projects I’ve worked on are encrypted point-to-point encryption, so a good project should be key negotiation

  • OnConnectionStateChange –> changeMTU(int) –>onMtuChanged()–> Gatt.discoverservices ()–>onCharacteristicRead()– > Check the value of the last read, because the project may have multiple hardware attributes, version number, etc

  • 7, the gatt is not in use

  • 8. If you are implementing a BLE module, it is recommended to use the state mode to implement the code, but it is important to note that the state management should not be messed up. If it is messed up, the state mode is more troublesome

  • 9, reconnect through connectByName Or connectByAddress this method to get BluetoothDevice in fact the address is the same, so directly use BluetoothDevice to connect, not so much

  • 10. Generally speaking, BLE devices are restored to factory Settings. If virtual MAC addresses are used at this time, the code needs more judgment, so the project maintains a currently connected device

  • 11. BLE will be reconnected automatically. In the actual process, if BLE is powered off and then powered on, it needs to be reconnected, but it is recommended to make a delay

  • All messages for BLE callbacks are in the same thread pool, so if you need to consider multiple threads in a particular scenario…

  • 13, status =133 is a normal phenomenon, if the probability is large, need to do processing

Tip:

  • A function only does one thing, the thing it changes to do
    • A function, if possible, to keep it within 20 lines (good) or one screen height (good)
    • If else logic is too deep, consider the way to extract, shunt, and unpack the hierarchy
    • Code blocks should not stick together, key places should be interlaced, and code blocks or new functions should be formed